2012-06-17 170 views
0

我试图设计在轨 模型协会是由以下3种类型:Rails的模型关联

评论员,博客帖子和评论

- >它的“评论员”,而不是“用户”是什么意味着 他们不是创建博客帖子的用户... 而是他们仅创建评论。

虽然评论员 和评论之间的基本关系是显而易见的:

class Commentator < ActiveRecord::Base 
    has_many :comments 

class Comment < ActiveRecord::Base 
    belongs_to: comments 

我不知道如何与“博客帖子”这个...... - >我想转到能问对于所有Blogposts 评论员已经离开以及特定博客帖子的所有评论员 。

由于这是一个多一对多的关系我 使用:

class Commentator < ActiveRecord::Base 
    has_many :comments 
    has_many :blogposts, :through => :comments 

class Blogpost < ActiveRecord::Base 
    "has_many :commentators, :through => :comments 

当评论员创建了一个博客帖子,我必须 写评论 的commenentator_id和blogpost_id由扑进评论表的相应字段?

我认为最好将Blogposts作为 ,因为关系可能是 当评论员创建评论时会自动构建。 (除了评论员不能创建评论 到不存在的博客帖子...) 但是,评论员评论不会是多对多的 关系,我不能使用“has_many ...通过“了。

什么是关联这3种模型的好方法?

回答

2

解决了上述问题,

class Commentator < ActiveRecord::Base 
    has_many :comments 
    has_many :blogposts, :through => :comments 
end 

class Comment < ActiveRecord::Base 
    belongs_to :commentator 
    belongs_to :blogpost 
end 

class Blogpost < ActiveRecord::Base 
    has_many :comments 
    has_many :commentators, :through => :comments 
    belongs_to :user 

class User 
    has_many :blogposts 
end 

要添加到现有的博客文章评论(假设我们有一个blogcommentator变量)

blog.comments.create(:commentator => commentator, :comment => "foo bar") 

OR

commentator.comments.create(:blog => blog, :comment => "foo bar") 

注意

而不是使用两个模型的用户(即,用户和评论者),我会使用一个模型并分配特权 来区分评论者和博客文章作者。

class User 
    has_many :blogs 
    has_many :comments 
    has_many :commented_blogs, :through => :comments, :source => :blog 
end 

class Blog 
    has_many :comments 
    belongs_to :user 
    has_many :commenters, :through => :comments, :source => :user 
end 

class Comment 
    belongs_to :user 
    belongs_to :blog 
end 
  • 创建博客条目:

    if current_user.has_role?(:blog_writer) 
        current_user.blogs.create(params[:blog]) 
    end 
    
  • 添加评论:

    current_user.comments.create(:blog => blog, :content => "foor bar") 
    

    OR

    blog.comments.create(:user => current_user, :content => "foor bar") 
    
+0

真棒帮助。谢谢... – JoeFrizz