2016-02-13 80 views
1

在一個模型上只使用belongs_to與在另一個模型上使用has_many而在另一個模型上使用has_many有什麼區別,另一個是belongs_toruby​​ on rails - 使用JUST'belongs_to'和使用'has_many'和'belongs_to'之間的區別?

舉個例子:

class Author < ActiveRecord::Base 
end 

class Book < ActiveRecord::Base 
    belongs_to :author 
end 

class Author < ActiveRecord::Base 
    has_many :books 
end 

class Book < ActiveRecord::Base 
    belongs_to :author 
end 

謝謝。

+0

沒有區別。該協會僅從加載模型的角度來看很重要。如果你有'class Book belongs_to:author',你可以調用'@ book.author';而你將不能*調用'@ author.books'。 –

+0

你應該看看[ORM](https://en.wikipedia.org/wiki/Object-relational_mapping)是如何工作的(其中'ActiveRecord'就是其中之一)。當你在你的模型中聲明一個「關聯」時,這只是給了「ActiveRecord」一個參考。它對基本級別的SQL沒有任何作用 –

回答

1

猜測每一種方法將有利於增加一組不同的其他方法,以關聯的類別

爲前,如果不得不去猜測,在一起belongs_to,你會在某種程度上,去呼籲的聯想能力的Book實例:

@book.author 

has_many,如果我猜的話,你會在某種程度上可以稱之爲協會實例Author

@author.books 

也,http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-belongs_to

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many

在那些情況下,可能會感興趣

相關問題