2010-01-22 114 views
3

我有兩個型號:rails belongs_to has_one。需要一些解釋

CustomerContact

Customers表中的列:id, :firstName, :lastName

Contacts表中的列:id, :cid, :hphone, :cphone

因此,如果客戶表中有數據

1 Josh McDonnel 

然後聯繫表中有相應的

5 1 947-245-2342 342-543-8585 

我可以使用什麼關聯嗎?

將聯繫有

belongs_to :customer, :foreign_key => "id", :class_name => "Customer" 

應該採取什麼Customer類有哪些?

此外,如何將一個簡單的find_byXXX樣子,如果我想獲得所有客戶(firstNamelastName和相應hphonecphone

回答

4

您近了,但您的belongs_to應該是這個。:foreign_key應該是該領域的存儲到主ID的引用名稱:

belongs_to :customer, :foreign_key => "cid" 

而在你Customer.rb類:

has_one :contact, :foreign_key => "cid" 

最後,你的搜索可能是這樣的:

@customers = Customer.all(:include => :contact) 

然後,您可以在您的視圖中以循環方式使用它:

<% @customers.each do |customer| %> 
    <p>Name: <%= customer.firstName %> <%= customer.lastName %></p> 
    <p>Home: <%= customer.contact.hphone %></p> 
    <p>Work: <%= customer.contact.cphone %></p> 
<% end %> 

順便說一句,如果你曾經使用customer_id代替cid您的關聯可能只是:

#Contact.rb 
belongs_to :customer 

#Customer.rb 
has_one :contact 
+0

感謝您的一個很好的解釋。我試圖做你提出的搜索,但在我的情況'cid'是varchar,但'id'是整數。以便搜索不起作用並拋出錯誤。我可以回去並將cid更改爲整數,但是可以說例如我不想改變它。將會有什麼工作呢? – Omnipresent 2010-01-22 22:05:02

+0

當然,只是運行一個遷移。 (備份你的數據!)運行這個:'script/generate migration ChangeContactsForeignKey'並使用下面的代碼:http://pastie.org/790513 – 2010-01-22 22:14:24

+0

當然,當你完成這些步驟時使用'rake db:migrate' – 2010-01-22 22:21:38

7

記住一個規則:在它belongs_to的表的外鍵的表那個外鍵引用。

1

表中的對象包含外鍵「belongs_to」不包含的對象。

如果客戶has_one聯繫人並聯系belongs_to客戶,則聯繫人表中將存在外鍵(默認爲「customer_id」)。

您可能不希望將「id」用作外鍵,因爲「id」是爲包含聯繫人ID的列保留的。指定類名也不是必需的,因爲類的名稱與關係的名稱相同(在本例中爲「customer」)。

客戶將有:

has_one :contact 

聯繫將有:

belongs_to :customer 

然後,如果你想找到某個客戶的聯繫,你可以只要致電:

@customer.contact 

或副反之亦然。

有關find_by_XXX的其他問題有點含糊。如果你想找到所有名字爲「John」的顧客,你可以使用:

@customers_named_john = Customer.find_by_firstName("John") 

但是我不確定這是你問的問題。

+0

在他的數據庫模式,看來他要存儲'Customer'的'id'在' cid'。 – 2010-01-22 21:58:02