【问题标题】:How to create this `through`` association?如何创建这个“通过”关联?
【发布时间】:2016-01-29 11:23:14
【问题描述】:

OrganizationLink 通过 Node 关联。

Organization:

has_many :nodes
has_many :links, through: :nodes, source: :where_first_links

Node:

belongs_to :organization
has_many :where_first_links, class_name:  "Link",
                             foreign_key: "first_node_id"
has_many :where_second_links, class_name:  "Link",
                              foreign_key: "second_node_id"

Link:

belongs_to :first_node,  class_name: "Node"
belongs_to :second_node, class_name: "Node"

问题::如何将Link 关联回Organization?我尝试了下面的行,但似乎不起作用(ArgumentError: Unknown key: :through.):

belongs_to :organization, 
           through: :first_node, 
           source: :where_first_links, 
           inverse_of: :links

【问题讨论】:

  • s/belongs_to/has_one/

标签: ruby-on-rails ruby ruby-on-rails-4 associations


【解决方案1】:

belongs_to 不支持通过 key 关联

你应该使用 has_one 关联

has_one :first_node_organization, 
        through: :first_node, 
        class_name: 'Organization', 
        source: :organization

【讨论】:

    【解决方案2】:

    使用has_one 代替belongs_to

    class Link < ActiveRecord::Base
      belongs_to :first_node,  class_name: "Node"
      belongs_to :second_node, class_name: "Node"
    
      has_one :organization, through: :first_node
    end
    

    【讨论】:

    • 谢谢,我试过了,但Link.first.organization 然后回复ActiveRecord::InverseOfAssociationNotFoundError: Could not find the inverse association for organization (:links in Link)
    • 啊,是的,很抱歉。我已经更正了我的答案(以防有人来看)。顺便说一句,如果您只是在链接:organization 上调用关联,则不需要指定class_namesource 选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多