【问题标题】:ruby on rails - difference between using JUST 'belongs_to' versus using BOTH 'has_many' and 'belongs_to'?ruby on rails - 使用 JUST 'belongs_to' 与同时使用 'has_many' 和 'belongs_to' 的区别?
【发布时间】:2016-02-13 01:44:01
【问题描述】:

在一个模型上仅使用 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

谢谢。

【问题讨论】:

  • 没有区别。关联仅从加载模型的角度来看很重要。如果你有class Book belongs_to :author,你就可以打电话给@book.author;而您将能够致电@author.books
  • 您应该了解ORM 的工作方式(其中ActiveRecord 非常重要)。当你在你的模型中声明一个“关联”时,这只是给ActiveRecord一个参考。它对基本级别的 SQL 没有任何作用

标签: sql ruby-on-rails has-many belongs-to


【解决方案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

如果这些可能感兴趣

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    相关资源
    最近更新 更多