看着铁轨例如这种结构的模型:两种模型如何访问对方?
,并在代码中,我们有:
class LineItem < ActiveRecord::Base
belongs_to :product
belongs_to :cart
attr_accessible :cart_id, :product_id
end
,并在模型中的“产品”类有一个方法这样的定义:
class Product < ActiveRecord::Base
has_many :line_items
private
# ensure that there are no line items referencing this product
def ensure_not_referenced_by_any_line_item
if line_items.empty?
return true
else
errors.add(:base, 'Line Items present')
return false
end
end
所以在哪里,我们甚至定义,我们使用它像line_items:line_items?它如何知道它指的是什么?它是否知道基于一些命名约定魔术?它如何将这个line_items连接到LineItems类?如果你能解释这两者如何连接在一起会很好。
啊我明白了。并且我们定义关联例如hasmany:XYZ这个XYZ必须以Rails通过查看它的名字了解哪个控制器的方式命名?例如,我们有一个名为line_items的控制器文件。因此,我们必须定义关联名称完全相同:line_items?感谢您的信息。 – Bohn
当你说'has_many:things'时,你会得到一个'.things'方法,一个'.create_thing'方法,以及所有其他的方法。默认情况下,符号(':things')与相关模型的名称('Thing')匹配,但它们不需要 - 如果不指定'has_many',则可以使用参数指定类名比赛。如果你这样做,这些方法基于符号而不是类名(因此关联是'has_many:things',但类是实际的'Widget',该方法仍然是'.things' – MrTheWalrus