Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails模型关联_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails Rails模型关联

Ruby on rails Rails模型关联,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试在rails中设计模型关联 由以下3种类型组成: 评论员、博客和评论 -->这是“评论员”而不是“用户”什么意思 他们不是创建博客帖子的用户。。。 相反,它们只创建注释 而评论员之间的基本关系 评论显而易见: class Commentator < ActiveRecord::Base has_many :comments class Comment < ActiveRecord::Base belongs_to: comments 课堂评论员

我正在尝试在rails中设计模型关联 由以下3种类型组成:

评论员、博客和评论

-->这是“评论员”而不是“用户”什么意思 他们不是创建博客帖子的用户。。。 相反,它们只创建注释

而评论员之间的基本关系 评论显而易见:

class Commentator < ActiveRecord::Base
    has_many :comments

class Comment < ActiveRecord::Base
    belongs_to: comments
课堂评论员
我不知道如何将“博客帖子”与此联系起来。。。 -->我想去能够要求所有的博客帖子 一位评论员和所有评论员都离开了 一篇特定的博客文章

因为这是一种多对多的关系,我 将使用:

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

class Blogpost < ActiveRecord::Base
    "has_many :commentators, :through => :comments
课堂评论员:评论
类Blogpost:评论
当评论员撰写博客文章时,我必须这样做吗 在评论中写下推荐人id和博客帖子id 由我自己进入注释表的相应字段

我认为最好是以博客帖子为基础 正在通过元素,因为关系可能是 评论员创建评论时自动生成。 (除了评论员不能发表评论之外 到不存在的博客帖子…) 但这样一来,发表评论的评论员就不会是多对多了 关系和我不能用“有很多。。。再也没有了


将这三种模型关联起来的好方法是什么?

针对所述问题的解决方案

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

注意

我将使用一个模型并分配权限,而不是为用户使用两个模型(即User和Commenter) 区分评论者和博客作者

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")
    

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