如何创建这个`through``协会?

时间:2016-01-29 11:23:15

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

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"

问题:如何将LinkOrganization关联?我尝试了以下这一行,但这似乎不起作用(ArgumentError: Unknown key: :through.):

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

2 个答案:

答案 0 :(得分:2)

belongs_to association not not key by key

你应该使用has_one association

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

答案 1 :(得分:1)

使用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