2016-02-13 85 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

在那些情况下,可能会感兴趣

相关问题