Rails 4 - 如何从“has_many - > belongs_to”关系中获取所有公司的列表?

时间:2016-03-01 02:30:13

标签: ruby-on-rails activerecord model rails-activerecord has-many

我有这种模型结构:

class OrganizationBlast < ActiveRecord::Base
  has_many :organization_blast_companies
end
class OrganizationBlastCompany < ActiveRecord::Base
  belongs_to :organization_blast
  belongs_to :company
end

如何获得爆炸中所有公司的列表? 到目前为止,我这样做:

organization_blast             = OrganizationBlast.find(params[:id])
organization_blast_companies   = organization_blast.organization_blast_companies.includes(:company)
organization_blast_companies.each do |organization_blast_company|
  puts organization_blast_company.company.name
  ...

我同意这里的命名惯例很疯狂。

但是,有没有更好的方法来获得组织爆炸中的公司名单?

谢谢

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找has_many :through关联。

按以下方式设置模型:

class OrganizationBlast < ActiveRecord::Base
  has_many :organization_blast_companies
  has_many :companies, through: :organization_blast_companies
end
class OrganizationBlastCompany < ActiveRecord::Base
  belongs_to :organization_blast
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :organization_blast_companies
  has_many :organization_blasts, through: :organization_blast_companies
end

然后,只需调用organisation_blast.companies即可获取与OrganizationBlast对象关联的所有公司。

organization_blast = OrganizationBlast.find(params[:id])
organization_blast_companies = organization_blast.companies

参考:http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

希望有所帮助:)