【问题标题】:has_many :through without a join tablehas_many :通过没有连接表
【发布时间】:2013-06-10 20:29:55
【问题描述】:

我正在查看一些设置 User 模型的示例 Rails 代码,如下所示:

has_many :posts, :foreign_key => :author_id
has_many :comments, :foreign_key => :author_id
has_many :post_feedback, :through => :posts, :source => :comments

虽然我可以理解这是做什么的,但我无法在 Rails 文档中找到此功能的示例,这似乎表明连接表对于 has_many :through 关联始终是必需的。

在不需要连接表的情况下,有没有我可以应用的经验法则?

【问题讨论】:

    标签: ruby-on-rails activerecord associations


    【解决方案1】:

    如果您觉得不需要加入模型,您可以使用has_and_belongs_to_many 执行此操作。但是您仍然需要数据库中的连接表。没有办法解决这个问题,因为这是用 RDBMS 建模多对多关系的唯一方法。

    如果您觉得不需要连接表,那么您可能有一对多或一对一的关系,可以使用belongs_tohas_one 进行配置,但这听起来不合理喜欢你的情况。

    【讨论】:

      【解决方案2】:

      我最初没有为正确的上下文发布足够的代码,但事实证明这是has_many :through, :source 习惯于(用 Rails 文档的话)“通过嵌套的 has_many 关联设置'快捷方式'的示例。 "

      class Post < ActiveRecord::Base
        belongs_to :author, :class_name => "User"
        has_many :comments, :foreign_key => :post_id
      end
      
      class Comment < ActiveRecord::Base
        belongs_to :author, :class_name => "User"
        belongs_to :post
        belongs_to :parent, :class_name => "Comment", :foreign_key => "parent_comment_id"
      
        has_many :replies, :class_name => "Comment", :foreign_key => "parent_comment_id"
      end
      
      class User < ActiveRecord::Base
        has_many :posts, :foreign_key => :author_id
        has_many :comments, :foreign_key => :author_id
        has_many :post_feedback, :through => :posts, :source => :comments
      end
      

      :post_feedback 只是嵌套关联的自定义名称(:comments 已被使用),:source 使实际关联显式化。现在 Rails 将理解 User.post_feedback 并返回给定 Users Posts 上的所有 Comments,包括她自己的。

      【讨论】:

        猜你喜欢
        • 2017-06-10
        • 2016-01-07
        • 2011-01-11
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多