我有这种模型结构:
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
...
我同意这里的命名惯例很疯狂。
但是,有没有更好的方法来获得组织爆炸中的公司名单?
谢谢
答案 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
希望有所帮助:)