两类模型如何相互访问?

时间:2013-01-21 16:15:40

标签: ruby-on-rails ruby-on-rails-3

查看具有此结构的rails示例:

enter image description here

在我们的代码中:

class LineItem < ActiveRecord::Base
  belongs_to :product
  belongs_to :cart
  attr_accessible :cart_id, :product_id
end

并且在“Product”类的模型中有一个定义如下的方法:

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类的?如果你能解释这两者如何连接在一起会很棒。

1 个答案:

答案 0 :(得分:2)

是的,这是工作中的'Rails魔术'。当您定义关联时(在这种情况下使用belongs_tohas_many,Rails会根据关联对象的名称创建一组方法。因此,在这种情况下,Product有一个方法{ {1}}添加了它,它返回一个Relation(基本上是一个表示数据库查询的对象)。当代码对该Relation执行某些操作时,它会执行查询并返回一个LineItem对象数组。

这也是Rails在您分配关联对象(.line_items)或创建新关联对象(@line_item.product = Product.find(3))等事情时知道您的意思的原因。

This guide提供详细信息,包括各种关联创建的方法列表。