繁体   English   中英

两类模型如何相互访问?

[英]How two classes of model are accessing each other?

查看具有此结构的rails示例及其模型:

在此处输入图片说明

在代码中,我们有:

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类? 如果您能解释这两个如何连接在一起,那就太好了。

是的,它正在发挥作用。 定义关联时(在这种情况下,通过使用belongs_tohas_many ,Rails基于关联对象的名称创建一堆方法。因此,在这种情况下,产品中添加了.line_items方法,该方法返回一个Relation(基本上是一个代表数据库查询的对象),当代码使用该Relation执行某些操作时,它将执行查询并返回LineItem对象的数组。

这也是Rails知道您执行诸如分配关联对象( @line_item.product = Product.find(3) )之类的事情或创建新的关联对象( @product.create_line_item(:title => 'foo') )。

本指南提供了详细信息,包括由各种关联创建的方法的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM