2014-02-16 169 views
0

我想爲我的模型找到正確的關聯,但無法弄清楚。Rails協會模型

我有3種型號,BatManufacturer,& Review。這裏是我的模型:

class Bat < ActiveRecord::Base 
    has_many :reviews 
    has_one :manufacturer 
end 

class Manufacturer < ActiveRecord::Base 
    has_many :bats 
end 

class Review < ActiveRecord::Base 
    belongs_to :bat 
end 

在審查模式,它有一個bat_id & manufacturer_id場。在蝙蝠模型中,它有一個manufacturer_id字段。

我想正確地將製造商模型鏈接到蝙蝠模型上。我看過http://guides.rubyonrails.org/association_basics.html#self-joins,我不確定那是我需要的那種類型的關係。

這是正確的還是我錯過了什麼?

回答

1

正如您通過自加入文檔所看到的,自加入用於將模型加入到自身中。您不需要這樣做,因爲製造商不以任何方式屬於其他製造商(至少,不是從我的描述中可以看出的)。

此外,您的評論模型不需要被鏈接到製造商模型(又名,你不需要審查模式manufacturer_id

你的蝙蝠模型應該有belongs_to :manufacturer,因爲它屬於製造商,它沒有一個你可以閱讀更多關於belongs_to VS has_one此:http://guides.rubyonrails.org/association_basics.html#choosing-between-belongs-to-and-has-one

所有你需要的是你的蝙蝠表manufacturer_id,並在您的審查表bat_id然後你就可以使用所有Rails魔術,就像

bat.manufacturer # get the manufacturer of a bat 
manufacturer.bats # get all the bats from a manufacturer 
bat.reviews # get all the reviews for a bat 

很顯然,您需要創建遷移到田裏你的蝙蝠類添加到數據庫中,如

rails generate migration add_manufacturer_id_to_bat manufacturer_id:integer 
rails generate migration add_bat_id_to_review bat_id:integer 
rake db:migrate 
+0

好感謝。我在我的評論表中使用了manufacturer_id,因爲它允許我使用兩個下拉選擇來設置表單。在一個下拉菜單中,用戶選擇製造商,在另一個下拉菜單中選擇球棒名稱。我想使用JavaScript(基於http://www.chasepursley.com/dynamic-select-slash-dropdown-menus-with-rails-3-plus-on-the-client-side)來允許一個好的用戶界面。如果僅基於動態下拉列表將bat_id存儲在評論表中將會很好,但我無法弄清楚。 (這就是爲什麼我有bat_id&manufacturer_id) – Daniel

+0

我一直想弄清楚如何解決這個問題在這裏http://stackoverflow.com/questions/21690556/rails-multiple-input-field-in-form-to-one -integer-attribute-in-model – Daniel

+0

我無法使'bat.manufacturer'工作,只有'bat.manufacturer_id'會顯示整數。 – Daniel

0

因爲您的製造商有很多蝙蝠,您的蝙蝠屬於一個製造商,所以我認爲更改has_one :manufacturerbelongs_to :manufacturer將解決您的問題。

-1

更改爲這是有道理的

class Bat < ActiveRecord::Base 
    has_many :reviews 
    belongs_to :manufacturer 
end 
+0

這個答案是正確的。該op說,蝙蝠「有一個製造商」,而製造商「有很多蝙蝠」。每個'has_many'或'has_one'需要在另一個模型上有一個'belongs_to'對應。在模型關聯的兩端不能有兩個'has_ *'。 – ahnbizcad