2010-09-15 49 views
4

例如,在在Rails中,使用「has_many with belongs_to」和「has_many with has_one」有什麼區別?

class Student < ActiveRecord::Base 
    has_many :awards 
end 

class Awards < ActiveRecord::Base 
    belongs_to :student 
end 

上面應該是正確的用法,但如果我們用

class Student < ActiveRecord::Base 
    has_many :awards 
end 

class Awards < ActiveRecord::Base 
    has_one :student 
end 

不上面也成爲可能student.awards作爲獎勵對象的數組什麼, award.student作爲獎項獲得者的學生對象,因此其工作方式與帖子頂部的方法相同?

+0

See:[Cardinality on wikipedia](http://en.wikipedia.org/wiki/Cardinality_(data_modeling%29) – NullUserException 2010-09-15 02:51:50

回答

7

has_one用於一對一的關係,而不是一對多的關係。

正確使用has_one

class Student < ActiveRecord::Base 
    has_one :id_card 
end 

class IdCard < ActiveRecord::Base 
    belongs_to :student 
end 
+3

關鍵是:具有'belongs_to'語句的類是外鍵類其表格模式。 – mikezter 2010-09-27 15:43:50

1

兩個例子是不等價的。

has_manybelongs_to在存在「多對一」關係的情況下作爲一對工作。

在數據庫中,這將是這樣的:

**Students** 
Name 
Email 
... 

**Awards** 
Name 
student_id <-- !IMPORTANT! 
... 

每個Student有很多獎項,因此has_many :awards 每個Award「屬於」一個Student因此belongs_to :student

注意,belongs_to被應用到表與外鍵student_id。這個很重要。

好的 - 那麼在發生'一對一'關係時會發生什麼?

如果每個學生只能獲得一個獎勵,那麼數據庫表格可能看起來完全一樣,但該模型不應該能夠返回一組項目。

這是我們需要has_one聲明的地方。在這種情況下,這將應用於Student模型。爲什麼?因爲這兩個方向的關係是相同的,但Active Record需要知道在哪裏可以找到外鍵。

如果數據庫表是周圍的其他方法,每個Student具有award_id那麼Student會得到belongs_toAward會得到has_one

希望明確嗎?

如果您使用自然語言,學生可能屬於一個獎項似乎有點奇怪。但是,這就是如何寫軌道活動記錄域特定語言。

當你看着'has_many_and_belongs_to'的'多對多'關係時,它聽起來更加不自然。這裏有一個表連接,你的主表之間的網站,如

students_awards 
student_id 
award_id 

在這種情況下,無論是Students也不Awards表有一個外鍵,但都將攜帶has_many_and_belongs_to :other_table聲明。兩個表都能夠連接到另一個的多行。每個Student可以有多個Award。每個Award可應用於許多Students

has_one聲明僅用於那裏是一個「一比一」的關係,並表它適用於不有外鍵。

相關問題