[英]Dealing with Comments in Ruby on Rails
Currently, I'm making a simple blog-like app, where a user can make a post, and several other users can comment on it. 目前,我正在制作一个简单的类似博客的应用程序,用户可以在其中发布信息,其他几个用户可以对此发表评论。
Is there a way to have a polymorphic attribute belong to more than one Model? 有没有一种方法可以使多态属性属于多个模型?
For example, 例如,
a Comment will always have an author (User model) However, a Comment can belong to many other models (Posts, Journals, Articles, etc etc) 评论将始终具有作者(用户模型)。但是,评论可以属于许多其他模型(帖子,期刊,文章等)
so, for (Posts, Journals, Articles) models, polymorphic association is best. 因此,对于(帖子,期刊,文章)模型,多态关联是最好的。 However, for the author (or User relationship), polymorphic would not work, since polymorphic can only belong to one at a time.
但是,对于作者(或用户关系)而言,多态无法正常工作,因为一次只能属于一个多态。
Is there a better way around this? 有没有更好的办法解决这个问题?
EDIT: What are the pros/cons of doing this: 编辑:什么是这样做的利弊:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :commentable, :polymorphic => true
end
EDIT2: with the solution above, is there a more elegant way of doing this EDIT2:使用上述解决方案,是否有更优雅的方法
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
without having to save the user_id manually in the controller? 无需在控制器中手动保存user_id?
@comment.user_id = current_user.id
You can have both a User
relationship as well as a polymorphic relationship representing the model it is associated with. 您既可以具有
User
关系,也可以具有表示与之关联的模型的多态关系。 For example: 例如:
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
Now, you can call comment.user
to get the User
model for the person who created the comment and comment.document
to get the Post
, Journal
, or Article
that the comment is associated with. 现在,你可以调用
comment.user
来获取User
模型谁创造了意见和人comment.document
拿到Post
, Journal
或Article
的评论与相关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.