![](/img/trans.png)
[英]In Rails, what is the difference using “has_many with belongs_to” vs “has_many with has_one”?
[英]Rails has_many through with has_one or belongs_to
我有3種型號:Company,Portable和Jobsite。 我希望能夠致電company.portables
, company.jobsites
, portable.company
, portable.jobsite
, jobsite.portables
和jobsite.company
。 我已經建立了這樣的關聯:
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
我可以成功調用一切,除了jobsite.company
。 撥打電話時,我得到:
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.
建立這些關聯的正確方法是什么? 我是否必須將工作場所與公司的關聯設置為工作場所上的belongs_to :company
,然后將jobsite_id添加到公司? 似乎應該用我已經設置的方法來實現此目的。
如果您考慮一下,所描述的架構將無法正常工作。 如果您真的希望Jobsite只有一家公司,那么它就無法通過Portable,因為Jobsite有很多Portable。
因此,您有兩個選擇:-如果您的意思是一個Jobsite應該有一個“主要”公司,那么直接有一個Jobsite has_one :company
,而沒有:through
部分。 -如果您要說的是工作現場,那么工作現場實際上可以通過許多便攜式計算機擁有許多公司,那么只需將代碼更改為have_many:
。
獎金選擇,您還可以通過執行以下操作來欣賞此處的選項:
has_one :company, -> {where(primary: true)}
您可以用這種方式來做各種花哨的事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.