【问题标题】:Dealing with Comments in Ruby on Rails在 Ruby on Rails 中处理注释
【发布时间】:2014-01-17 11:00:01
【问题描述】:

目前,我正在制作一个简单的类似博客的应用,用户可以在其中发帖,其他几个用户可以对其发表评论。

有没有办法让一个多态属性属于多个模型?

例如,

评论总是有作者(用户模型) 但是,评论可以属于许多其他模型(帖子、期刊、文章等)

因此,对于(Posts、Journals、Articles)模型,多态关联是最好的。 但是,对于作者(或用户关系),多态是行不通的,因为多态一次只能属于一个。

有没有更好的解决方法?

编辑: 这样做有什么好处/坏处:

class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :commentable, :polymorphic => true
end

编辑2: 使用上面的解决方案,有没有更优雅的方法来做到这一点

def create
    @comment = @commentable.comments.new(params[:comment])
    @comment.user_id = current_user.id

    if @comment.save
        flash[:success] = 'Comment created'
        redirect_to @commentable
    else
        flash[:error] = 'Comment not created - is body empty?'
        redirect_to @commentable
    end
end

无需在控制器中手动保存 user_id?

    @comment.user_id = current_user.id

【问题讨论】:

    标签: ruby-on-rails ruby database-design ruby-on-rails-4


    【解决方案1】:

    您可以同时拥有User 关系以及表示与其关联的模型的多态关系。例如:

    class Comment < ActiveRecord::Base
      belongs_to :user
      belongs_to :document, polymorphic: true
    end
    
    class Post < ActiveRecord::Base
      has_many :comments, as: :document
    end
    
    class Journal < ActiveRecord::Base
      has_many :comments, as: :document
    end
    
    class Article < ActiveRecord::Base
      has_many :comments, as: :document
    end
    
    class User < ActiveRecord::Base
      has_many :comments
    end
    

    现在,您可以调用comment.user 获取创建评论的人的User 模型,并调用comment.document 获取与评论关联的PostJournalArticle .

    【讨论】:

    • 抱歉,您对我的 EDIT2 有何看法?
    • 类似于如何使用comment.usercomment.document 获取模型,您也可以分配它们:comment.user = current_usercomment.document = current_document。当您 save 评论时,它会正确分配数据库中的 user_iddocument_iddocument_type 列。
    • 就优雅而言,您所做的一切都很好。
    猜你喜欢
    • 2021-08-09
    • 2011-10-12
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多