简体   繁体   English

Rails has_many通过has_one或belongs_to

[英]Rails has_many through with has_one or belongs_to

I have 3 models: Company, Portable and Jobsite. 我有3种型号:Company,Portable和Jobsite。 I want to be able to call company.portables , company.jobsites , portable.company , portable.jobsite , jobsite.portables and jobsite.company . 我希望能够致电company.portablescompany.jobsitesportable.companyportable.jobsitejobsite.portablesjobsite.company I've setup my associations like this: 我已经建立了这样的关联:

class Company
  has_many :portables
  has_many :jobsites, through: :portables
end

class Portable
  belongs_to :company
  belongs_to :jobsite
end

class Jobsite
  has_many :portables
  has_one  :company, through: :portables
end

I can call everything successfully except jobsite.company . 我可以成功调用一切,除了jobsite.company When I make this call, I get: 拨打电话时,我得到:

ActiveRecord::HasOneThroughCantAssociateThroughCollection: Cannot have a has_one :through association 'Jobsite#company' where the :through association 'Jobsite#portables' is a collection. Specify a has_one or belongs_to association in the :through option instead.

What is the proper way to setup these associations? 建立这些关联的正确方法是什么? Do I have to make the jobsite to company association a belongs_to :company on the jobsite and add the jobsite_id to the company? 我是否必须将工作场所与公司的关联设置为工作场所上的belongs_to :company ,然后将jobsite_id添加到公司? It seems there should be another way to achieve this with what I have already setup. 似乎应该用我已经设置的方法来实现此目的。

If you think about it, the schema as described just can't work. 如果您考虑一下,所描述的架构将无法正常工作。 If you really want Jobsite to have only one Company, then it can't go through Portable, bevause Jobsite has many Portables. 如果您真的希望Jobsite只有一家公司,那么它就无法通过Portable,因为Jobsite有很多Portable。

So your left with two choices: - If what you mean is one Jobsite should have a 'main' company, then have a Jobsite has_one :company directly, without the :through part. 因此,您有两个选择:-如果您的意思是一个Jobsite应该有一个“主要”公司,那么直接有一个Jobsite has_one :company ,而没有:through部分。 - If what you mean is thay Jobsites can really have many Companies through their many Portables, then just change your code to have_many: . -如果您要说的是工作现场,那么工作现场实际上可以通过许多便携式计算机拥有许多公司,那么只需将代码更改为have_many:

Bonus choice, you can also get fancy with the options here by doing something like: 奖金选择,您还可以通过执行以下操作来欣赏此处的选项:

has_one :company, -> {where(primary: true)}

You can do all kinds of fancy stuff that way. 您可以用这种方式来做各种花哨的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM