Has_many 通过关联无效

Has_many through association not working

在我的 Node 模型中,我有以下关联,其中两个 nodesLink 模型中被 linked:

has_many :first_links, class_name:  "Link",
                       foreign_key: "first_node_id"
has_many :second_links, class_name:  "Link",
                        foreign_key: "second_node_id"
belongs_to :organization

我基本上只想将所有 link 关联到一个节点,而不管该节点是 first_node 还是 second_node。因此,我在 Node 模型中也有以下方法:

def links
  first_links + second_links
end

如果我现在在控制台中尝试 Node.first.links,那么它会起作用,我会得到该节点的所有 link 的列表,无论该节点是 link 的第一个还是第二个节点 link。因此,这种关系似乎正在发挥作用。

Organization 模型中我有:

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

但是,控制台中的 Organization.first.links 生成错误:

Could not find the source association(s) "link" or :links in model Node.

我对 through 协会做错了什么?


更新: 我现在明白我需要一个自定义方法来收集 organization 的所有 links。以下对我来说最有意义(添加到 Organization 模型):

has_many :nodes
def links
  nodes.each do |node|
    self.links ||= []            #Create the array if it doesn't exist yet.
    links << node.links.collect  #Add all the links to the array.
  end
end

如果我在控制台中尝试 Organization.first.links,则会产生以下错误。知道该方法应该是什么样子吗?

/usr/local/rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:282:in `blame_file!': can't modify frozen fatal (RuntimeError)

嗯……

您只能调用 organization.nodes 而不能调用 organization.links,因为那只是 Node class.

中的一个方法

然而,您可以尝试在 Organization class 中创建一个类似的方法(这将是一个实例方法),以 return 所有节点的所有链接属于调用新创建方法的 Organization 的实例。

例如:

def links
  self.nodes.joins(:first_links) + self.nodes.joins(:second_links)
end