【发布时间】: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