diff --git a/README.md b/README.md
index 1de2d3e..25bf38a 100644
--- a/README.md
+++ b/README.md
@@ -17,7 +17,7 @@ git push -u origin master
## 3. 制作首页(静态页面)
1. 在 config/routes.rb文件中添加 `root to: 'visitors#index'`
2. `rails s` 启动服务器,访问 `http://localhost:3000`。 遇到报错,提示 `没有初始化的常量 VisitorsController` (记得git commit)
- 插入报错图片
+ 
3. 命令行运行 `rails g controller visitors index`; 再访问 `http://localhost:3000`, 无报错信息。
4. 使用[Bootstrap](http://getbootstrap.com)制作前端
- 观看[Gorails视频](https://gorails.com/episodes/styling-with-bootstrap-sass) (观看时把字幕打开), 以及参考 [bootstrap-sass](https://github.com/twbs/bootstrap-sass)
@@ -33,8 +33,8 @@ git push -u origin master
//= require bootstrap-sprockets
```
- `git commit -m 'add bootstrap'`
- - `http://www.bootcss.com/p/layoutit/` 可视化布局首页
- 插入图片
+ - `http://www.bootcss.com/p/layoutit/` 可视化布局首页(我去这个地方下载了一个博客模板,省掉了自己写前端 https://startbootstrap.com/template-categories/all/ 。这个可能会增加复杂度,建议大家还是用模板工具,搭建简单的页面即可)
+ 
- 下载代码,粘贴到 `app/views/visitors/index.html.erb`
- 修改上一步的代码,并把引用的图片放到 `app/assetts/images`文件夹中
- 创建共享文件夹 `mkdir app/views/shared`
@@ -55,6 +55,7 @@ git push -u origin master
## 4. 用户注册&登录
使用[devise](https://github.com/plataformatec/devise)配置用户注册和登录功能。
看「GEtting started」完成登录功能:
+
1. 在Gemfile文件中添加 `gem 'devise'`, 然后在命令行运行 `bundle install`
2. 在命令行运行 `rails g devise:install`;
3. 在文件config/environments/development.rb 中添加:
@@ -69,7 +70,9 @@ git push -u origin master
```
然后在运行 `rails db:migrate` 迁移数据库
-7. permit additional parameters (the lazy way™), you can do so using a simple before filter in your ApplicationController:
+7. 在文件app/application_controller.rb增添如下代码,目的是让devise的用户注册功能能写入数据库字段 `:username`
+ > permit additional parameters (the lazy way™), you can do so using a simple before filter in your ApplicationController:
+
```
class ApplicationController < ActionController::Base
before_action :configure_permitted_parameters, if: :devise_controller?
@@ -81,11 +84,25 @@ git push -u origin master
end
end
```
-7. 在命令行输入 `rake routes` ,可以看到安装devise之后允许的路径,如下图:
-6. 修改导航栏中的用户和注册路径,启动服务器,测试注册和登录功能
-7. git commit
+8. 在命令行输入 `rake routes` ,可以看到安装devise之后允许的路径,如下图:
+9. 修改导航栏中的用户和注册路径,启动服务器,测试注册和登录功能. 请参考我的源码。
+10. git commit
## 5. Articles MVC实践
+
+> 网站 = 算法 + 数据(数据是核心)
+> MVC就是算法,我们写算法的步骤就如上图。
+>
+> 1. 从步骤1开始,浏览器输入网址。
+> 2. 浏览器到路由(config/routes.rb)
+> 3. 路由解析浏览器传过来的网址,传到相对应controller里面的action;
+> 4. action里面的方法决定从Model里面拿什么数据回来;
+> 5. 在Model层面写好模型的数据类型以及相关模型的关联关系;
+> 6. 把需要的数据给controller
+> 7. controller拿到数据以后,保存在实例变量里面,传给view层;
+> view层渲染上html/css/javascripts,再返回给controller;
+> 8. controller发送给浏览器
+
1. 修改导航栏中Articles的路径
```
@@ -93,10 +110,12 @@ git push -u origin master
```
2. 刷新浏览器,点击导航栏Articles,跳转到 `http://localhost:3000/articles`,报错,如下图:
+
3. `routes.rb` 中添加 `resources :articles`
4. 启动服务器 `rails s`, 访问 `http://localhost:3000/articles`, **找不到路径**错误已解决。但有一个新的 **找不到controller** 报错,报错如下图
- 插入图
+ 
5. 在命令行输入 `rails g controller articles`, 刷新浏览器。报错,提示controller里面没有 ‘index’ action,如下图:
+
6. 在 app/controllers/articles_controller.rb 文件夹中添加index方法
```
class ArticlesController < ApplicationController
@@ -106,14 +125,14 @@ git push -u origin master
```
再刷新浏览器。报错,提示:没有 index template
-7. 在命令行中输入 `touch app/views/articles/index.html.erb`
+7. 新建index页面:在命令行中输入 `touch app/views/articles/index.html.erb`
8. 再使用[可视化bootstrap工具](http://www.bootcss.com/p/layoutit/)制作文章页面,把代码复制过来。如下图效果:
9. 上面的还都是静态页面,没有model。现在我们开始**建立artile的model及其与其他模型的关联**:
- - 在命令行输入 `rails g model Article title:string content:text is_public:boolean category:references user:belongs_to`
- - `rails model Category name:string` : Article模型和Category模型是关联模型
- - `rails db:migrate`
- - 在 app/models/category.rb 添加内容如下
+ - 创建Article Model:在命令行输入 `rails g model Article title:string content:text is_public:boolean category:references user:belongs_to`
+ - 创建Category Model:`rails model Category name:string` : Article模型和Category模型是关联模型
+ - 数据迁移:`rails db:migrate`
+ - 模型关系:在 app/models/category.rb 添加内容如下
```
class Category < ApplicationRecord
has_many :articles
@@ -129,7 +148,7 @@ git push -u origin master
has_many :articles
end
```
- - 在db/seeds.rb 中添加如下内容
+ - 初始化数据:在db/seeds.rb 中添加如下内容
```
Category.find_or_create_by(name: "Science")
Category.find_or_create_by(name: "Technology")
@@ -138,14 +157,14 @@ git push -u origin master
Category.find_or_create_by(name: "Math")
```
在命令行运行 `rails db:seed` 初始化categories表格的数据
- - 完善articles_controller.rb中的index方法:从数据库中读入数据(C-M的数据交流)
+ - 让controller从model里面拿数据:完善articles_controller.rb中的index方法:从数据库中读入数据(C-M的数据交流)
```
def index
@articles = Article.where(is_public: true).order('created_at DESC')
end
```
- 完善 app/views/articles/index.html.erb
-10. 做完article的CRUD功能, 从controller到view的顺序更新。分别是:`show -> edit -> update -> new -> create -> destroy`
+10. 按照index的步骤做完article的CRUD功能, 从controller到view的顺序更新。分别是:`show -> edit -> update -> new -> create -> destroy`
- show
- 分享插件: http://www.jiathis.com
- edit
@@ -155,26 +174,85 @@ git push -u origin master
- http://www.printshit.me/blog/2016/05/30/how-to-use-simditor-in-rails/
- https://ruby-china.org/topics/28467
-6. Comment 实践(Polymorphic Association)
- 1. Creating a Single Comment Model
- `rails g model comment content:text commentable_id:integer commentable_type:string`
- 2. 修改 migration, 使用多态技巧polymorphic如下:
- ```
- class CreateComments < ActiveRecord::Migration[5.0]
- def change
- create_table :comments do |t|
- t.text :content
- t.belongs_to :commentable, polymorphic: true
-
- t.timestamps
- end
- add_index :comments, [:commentable_id, :commentable_type]
- end
+## 6. Comment 实践(Polymorphic Association)
+#### 6.1 Creating a Single Comment Model
+1. 创建模型:命令行中运行 `rails g model Comment content:text commentable:references{polymorphic} user:belongs_to`
+2. 添加相关模型关联关系:
+ ```
+ # app/model/user.rb
+ class User < ApplicationRecord
+ # Include default devise modules. Others available are:
+ # :confirmable, :lockable, :timeoutable and :omniauthable
+ devise :database_authenticatable, :registerable,
+ :recoverable, :rememberable, :trackable, :validatable
+ has_many :articles
+ has_many :comments, as: :commentable
+ end
+ ```
+
+ ```
+ class Article < ApplicationRecord
+ belongs_to :category
+ belongs_to :user
+ has_many :comments, as: :commentable
+ end
+ ```
+
+3. 然后 `rails db:migrate`
+#### 6.2 Using a Polymorphic Association in our Application
+1. 修改路由
+ ```
+ # config/routes.rb
+ resources :articles do
+ resources :comments, only: [:index, :new, :create]
+ end
+ ```
+2. 创建controller `rails g controller comments index new`
+3. 修改index 方法,从Comment模型读取数据
+ ```
+ def index
+ @commentable = Article.find(params[:article_id])
+ @comments = @commentable.comments
+ end
+ ```
+4. 修改 app/views/comments/index.html.erb 内容如下:
+ ```
+ # app/views/comments/index.html.erb
+ Comments
+ <%= render 'comments' %>
+ ```
+ ```
+ # app/views/comments/_comment.html.erb
+
+ <% @comments.each do |comment| %>
+
+ <% end %>
+ ```
+4. 在 `app/views/articles/show.html.erb` 文章内容下添加:
+ ```
+ <%= render "comments/comments" %>
+ ```
+ 启动服务器, 访问`http://localhost:3000/articles/1`,报错:提示each的对象 @comments 不能为空。因此我们要在article controller的show action里面添加存取出@comments的方法
+5. 更改 `app/controllers/articles_controller.rb` show de action
+ ```
+ def show
+ @categories = Category.all
+ # prepare comment instance variables for comment view partials
+ @commentable = @article
+ @comments = @commentable.comments.order('created_at DESC')
+ @comment = Comment.new
end
```
- 然后 `rails db:migrate`
+6.
- http://railscasts.com/episodes/154-polymorphic-association-revised?view=asciicast
- https://rubyplus.com/articles/3901-Polymorphic-Association-in-Rails-5
- https://gorails.com/episodes/comments-with-polymorphic-associations
- https://github.com/gorails-screencasts/gorails-episode-36
+- http://railscasts.com/episodes/154-polymorphic-association-revised?view=asciicast
+- https://rubyplus.com/articles/3901-Polymorphic-Association-in-Rails-5
+- https://gorails.com/episodes/comments-with-polymorphic-associations
+- https://github.com/gorails-screencasts/gorails-episode-36
diff --git a/app/assets/javascripts/comments.coffee b/app/assets/javascripts/comments.coffee
new file mode 100644
index 0000000..24f83d1
--- /dev/null
+++ b/app/assets/javascripts/comments.coffee
@@ -0,0 +1,3 @@
+# Place all the behaviors and hooks related to the matching controller here.
+# All this logic will automatically be available in application.js.
+# You can use CoffeeScript in this file: http://coffeescript.org/
diff --git a/app/assets/stylesheets/comments.scss b/app/assets/stylesheets/comments.scss
new file mode 100644
index 0000000..3722c12
--- /dev/null
+++ b/app/assets/stylesheets/comments.scss
@@ -0,0 +1,3 @@
+// Place all the styles related to the comments controller here.
+// They will automatically be included in application.css.
+// You can use Sass (SCSS) here: http://sass-lang.com/
diff --git a/app/controllers/articles_controller.rb b/app/controllers/articles_controller.rb
index cfd53a0..9ae151e 100644
--- a/app/controllers/articles_controller.rb
+++ b/app/controllers/articles_controller.rb
@@ -7,6 +7,10 @@ def index
def show
@categories = Category.all
+ # prepare comment instance variables for comment view partials
+ @commentable = @article
+ @comments = @commentable.comments.order('created_at DESC')
+ @comment = Comment.new
end
def edit
diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb
new file mode 100644
index 0000000..5bb67be
--- /dev/null
+++ b/app/controllers/comments_controller.rb
@@ -0,0 +1,32 @@
+class CommentsController < ApplicationController
+ before_action :authenticate_user!, except: [:index]
+ before_action :load_commentable
+
+ def index
+ @comments = @commentable.comments
+ end
+
+ def new
+ @comment = @commentable.comments.new
+ end
+
+ def create
+ @comment = @commentable.comments.new(comment_params)
+ @comment.user = current_user
+ if @comment.save
+ redirect_to @commentable, notice: "评论成功"
+ else
+ render :new
+ end
+ end
+
+ private
+ def load_commentable
+ resource, id = request.path.split('/')[1,2]
+ @commentable = resource.singularize.classify.constantize.find(id)
+ end
+
+ def comment_params
+ params.require(:comment).permit(:content, :user_id)
+ end
+end
diff --git a/app/helpers/comments_helper.rb b/app/helpers/comments_helper.rb
new file mode 100644
index 0000000..0ec9ca5
--- /dev/null
+++ b/app/helpers/comments_helper.rb
@@ -0,0 +1,2 @@
+module CommentsHelper
+end
diff --git a/app/models/article.rb b/app/models/article.rb
index 9c5f63c..3ec8bb5 100644
--- a/app/models/article.rb
+++ b/app/models/article.rb
@@ -1,4 +1,5 @@
class Article < ApplicationRecord
belongs_to :category
belongs_to :user
+ has_many :comments, as: :commentable
end
diff --git a/app/models/comment.rb b/app/models/comment.rb
new file mode 100644
index 0000000..d39d62d
--- /dev/null
+++ b/app/models/comment.rb
@@ -0,0 +1,4 @@
+class Comment < ApplicationRecord
+ belongs_to :commentable, polymorphic: true
+ belongs_to :user
+end
diff --git a/app/models/user.rb b/app/models/user.rb
index c3c343b..0d5ad01 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -4,4 +4,5 @@ class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :articles
+ has_many :comments, as: :commentable
end
diff --git a/app/views/articles/show.html.erb b/app/views/articles/show.html.erb
index 8c8f027..d140a09 100644
--- a/app/views/articles/show.html.erb
+++ b/app/views/articles/show.html.erb
@@ -19,7 +19,9 @@
<%= raw @article.content %>
-
+
+ <%= render "comments/form" %>
+ <%= render "comments/comments" %>
diff --git a/app/views/comments/_comments.html.erb b/app/views/comments/_comments.html.erb
new file mode 100644
index 0000000..4ee6411
--- /dev/null
+++ b/app/views/comments/_comments.html.erb
@@ -0,0 +1,12 @@
+# app/views/comments/_comment.html.erb
+
+<% @comments.each do |comment| %>
+
+<% end %>
\ No newline at end of file
diff --git a/app/views/comments/_form.html.erb b/app/views/comments/_form.html.erb
new file mode 100644
index 0000000..aa62689
--- /dev/null
+++ b/app/views/comments/_form.html.erb
@@ -0,0 +1,23 @@
+
+
Leave a Comment
+
+ <%= form_for [@commentable, @comment] do |f| %>
+ <% if @comment.errors.any? %>
+
+
Please correct the following errors.
+
+ <% @comment.errors.full_messages.each do |msg| %>
+ - <%= msg %>
+ <% end %>
+
+
+ <% end %>
+
+
+ <%= f.text_area :content, rows: 5, class: 'form-control' %>
+
+
+ <%= f.submit %>
+
+ <% end %>
+
\ No newline at end of file
diff --git a/app/views/comments/index.html.erb b/app/views/comments/index.html.erb
new file mode 100644
index 0000000..dcca44f
--- /dev/null
+++ b/app/views/comments/index.html.erb
@@ -0,0 +1,3 @@
+Comments
+<%= render 'comments' %>
+
diff --git a/app/views/comments/new.html.erb b/app/views/comments/new.html.erb
new file mode 100644
index 0000000..96486a3
--- /dev/null
+++ b/app/views/comments/new.html.erb
@@ -0,0 +1 @@
+<%= render 'form' %>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 64c45b6..a9c0f52 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,6 +1,12 @@
Rails.application.routes.draw do
+ get 'comments/index'
+
+ get 'comments/new'
+
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root to: 'visitors#index'
- resources :articles
+ resources :articles do
+ resources :comments, only: [:index, :new, :create]
+ end
end
diff --git a/db/migrate/20160908124243_create_comments.rb b/db/migrate/20160908124243_create_comments.rb
new file mode 100644
index 0000000..f822195
--- /dev/null
+++ b/db/migrate/20160908124243_create_comments.rb
@@ -0,0 +1,11 @@
+class CreateComments < ActiveRecord::Migration[5.0]
+ def change
+ create_table :comments do |t|
+ t.text :content
+ t.references :commentable, polymorphic: true
+ t.belongs_to :user, foreign_key: true
+
+ t.timestamps
+ end
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 943623c..ae78080 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema.define(version: 20160901141339) do
+ActiveRecord::Schema.define(version: 20160908124243) do
create_table "articles", force: :cascade do |t|
t.string "title"
@@ -30,6 +30,17 @@
t.datetime "updated_at", null: false
end
+ create_table "comments", force: :cascade do |t|
+ t.text "content"
+ t.string "commentable_type"
+ t.integer "commentable_id"
+ t.integer "user_id"
+ t.datetime "created_at", null: false
+ t.datetime "updated_at", null: false
+ t.index ["commentable_type", "commentable_id"], name: "index_comments_on_commentable_type_and_commentable_id"
+ t.index ["user_id"], name: "index_comments_on_user_id"
+ end
+
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
diff --git a/test/controllers/comments_controller_test.rb b/test/controllers/comments_controller_test.rb
new file mode 100644
index 0000000..1e08c8d
--- /dev/null
+++ b/test/controllers/comments_controller_test.rb
@@ -0,0 +1,14 @@
+require 'test_helper'
+
+class CommentsControllerTest < ActionDispatch::IntegrationTest
+ test "should get index" do
+ get comments_index_url
+ assert_response :success
+ end
+
+ test "should get new" do
+ get comments_new_url
+ assert_response :success
+ end
+
+end
diff --git a/test/fixtures/comments.yml b/test/fixtures/comments.yml
new file mode 100644
index 0000000..e5a5864
--- /dev/null
+++ b/test/fixtures/comments.yml
@@ -0,0 +1,13 @@
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
+
+one:
+ content: MyText
+ commentable: one
+ commentable_type: Commentable
+ user: one
+
+two:
+ content: MyText
+ commentable: two
+ commentable_type: Commentable
+ user: two
diff --git a/test/models/comment_test.rb b/test/models/comment_test.rb
new file mode 100644
index 0000000..b6d6131
--- /dev/null
+++ b/test/models/comment_test.rb
@@ -0,0 +1,7 @@
+require 'test_helper'
+
+class CommentTest < ActiveSupport::TestCase
+ # test "the truth" do
+ # assert true
+ # end
+end