需求:给图书表添加评论功能,类似豆瓣图书评论,book.rb:
class CreateBooks < ActiveRecord::Migration
def change
create_table :books do |t|
t.string :name
t.string :author
t.string :publish
t.text :abstract
t.string :picture_url
t.string :course
t.timestamps null: false
end
end
end
1.生成模型
rails generate model Comment commenter:string body:text book:references
运行迁移:
rake db:migrate
2.模型关联
打开/app/models/comment.rb,生成comment模型时已关联book
class Comment < ActiveRecord::Base
belongs_to :book
end
打开/app/models/book.rb,book和comment关联:
class Book < ActiveRecord::Base
mount_uploader :picture_url, AvatarUploader
has_many :comments
...
validates :picture_url, presence:true
end
一篇文章可以有多个评论,是一对多的关系,因此book中用has_many关联comment;而一条评论只能属于一本书,一对一的关系,因此用belongs_to。
3.添加评论的路由
打开/config/routes.rb,添加下面代码:
resources :books do
resources :comments
end
把 comments 放在 books 中,叫做嵌套资源,表明了文章和评论间的层级关系。
4.生成控制器
创建模型完成后,创建控制器
rails generate controller Comments
修改显示book的视图/app/views/books/show.html.erb,运行游客发表评论:
<h2>Add a comment:</h2>
<%= form_for([@book, @book.comments.build]) do |f| %>
<p>
<%= f.label :commenter %><br>
<%= f.text_field :commenter %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
修改CommentsController 控制器,创建评论:
class CommentsController < ApplicationController
def create
@book = Book.find(params[:book_id])
@comment = @book.comments.create(comment_params)
redirect_to book_path(@book)
end
private
def comment_params
params.require(:comment).permit(:commenter, :body)
end
end
在模版中显示评论,把显示评论的代码加入/app/views/books/show.html.erb:
<h2>评论</h2>
<% @book.comments.each do |comment| %>
<p>
<strong>Commenter:</strong>
<%= comment.commenter %>
</p>
<p>
<strong>Comment:</strong>
<%= comment.body %>
</p>
<% end %>
下面是实际效果: