评论多个模型

在我的rails应用程序中,我目前有评论设置可以使用我的post模型,它正常运行。 如何在我的图书模型中添加评论?

这是我到目前为止:

以下是我的架构中的评论内容:

create_table "comments", force: true do |t| t.text "body" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" t.integer "post_id" t.integer "book_id" end 

在我的用户模型中:

 class User < ActiveRecord::Base has_many :comments acts_as_voter end 

在我的post模型中:

 class Post < ActiveRecord::Base has_many :comments end 

在我的书模型中:

 class Book < ActiveRecord::Base has_many :comments end 

在我的评论模型中:

 class Comment < ActiveRecord::Base belongs_to :post belongs_to :book belongs_to :user acts_as_votable end 

在我的评论控制器中:

 class CommentsController < ApplicationController def create post.comments.create(new_comment_params) do |comment| comment.user = current_user end respond_to do |format| format.html {redirect_to post_path(post)} end end def upvote @post = Post.find(params[:post_id]) @comment = @post.comments.find(params[:id]) @comment.liked_by current_user respond_to do |format| format.html {redirect_to @post} end end private def new_comment_params params.require(:comment).permit(:body) end def post @post = Post.find(params[:post_id]) end end 

在我的路线文件中:

 resources :posts do resources :comments do member do put "like", to: "comments#upvote" end end end 

在我看来:

          

"80", :rows => "10" %>

我可以添加到评论控制器中以获取有关post和书籍的评论吗? 我将什么添加到我的路线文件中?

在此先感谢您的帮助。

您不希望指定可以容纳Comment对象的每种类型的对象。 这造成了if-elsif-else在整个地方阻塞的头痛。 相反,你想要的东西是可评价的,它们都会有.comments

这在Active Record中称为多态关联 。 所以你会让你的模型像:

 class Comment < ActiveRecord::Base belongs_to :commentable, polymorphic: true end class Post < ActiveRecord::Base has_many :comments, as: :commentable end class Book < ActiveRecord::Base has_many :comments, as: :commentable end 

并相应地修改您的数据库,这些都在链接的文章中。 现在,当您为表单构建一个Comment对象时,它将预先填充一个commentable_idcommentable_type ,您可以将其放入隐藏字段中。 现在Comment与之相关的并不重要,您始终将其视为相同。

我将User作为一个单独的关联,因为它不是真的相同的想法。