Rails嵌套模型获取字段

时间:2014-04-10 16:42:49

标签: ruby-on-rails ruby activerecord

在我的应用程序中,我有这样的模型结构:

class Organization < ActiveRecord::Base
  belongs_to :organization_type
  has_many :organization_type_links, :dependent => :destroy
end

class OrganizationType < ActiveRecord::Base
  has_many :organizations
  has_many :organization_type_links
end

class OrganizationTypeLink < ActiveRecord::Base
  belongs_to :organization
  belongs_to :organization_type
end

所以OrganizationTypeLink是一个链接表,我怎么能通过它获取OrganizationType.t_name?

就像我写的那样:

= @ organization.organization_type_links.t_name

这是真的吗?以及如何做到正确?

1 个答案:

答案 0 :(得分:0)

@organization.organization_type_links是一个数组。请尝试以下方法在t_name上调用organization_type方法:

@organization.organization_type_links.collect{|link| link.organization_type.t_name}

返回任何t_name返回的数组。