本文共 1870 字,大约阅读时间需要 6 分钟。
需求:给图书表添加评论功能,类似豆瓣图书评论,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 endend
rails generate model Comment commenter:string body:text book:references
运行迁移:
rake db:migrate
打开/app/models/comment.rb,生成comment模型时已关联book
class Comment < ActiveRecord::Base belongs_to :bookend
打开/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。
打开/config/routes.rb,添加下面代码:
resources :books do resources :commentsend
把 comments 放在 books 中,叫做嵌套资源,表明了文章和评论间的层级关系。
创建模型完成后,创建控制器
rails generate controller Comments
修改显示book的视图/app/views/books/show.html.erb,运行游客发表评论:
Add a comment:
<%= form_for([@book, @book.comments.build]) do |f| %><%= f.label :commenter %>
<%= f.text_field :commenter %><%= f.label :body %>
<%= f.text_area :body %><%= f.submit %>
<% 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) endend
在模版中显示评论,把显示评论的代码加入/app/views/books/show.html.erb:
评论
<% @book.comments.each do |comment| %>Commenter: <%= comment.commenter %>
Comment: <%= comment.body %>
<% end %>
下面是实际效果: