简体   繁体   English

两类模型如何相互访问?

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

Looking at a rails example with this structure for its models: 查看具有此结构的rails示例及其模型:

在此处输入图片说明

and in the code we have: 在代码中,我们有:

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

and in the model for "Product" class there is a method defined like this: 在“ 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

So where did we even define line_items that we are using it like :line_items? 那么,我们甚至在哪里定义了像:line_items这样使用的line_items? and how does it know what does it refer to? 它怎么知道它指的是什么? Does it know based on some naming conventions magic? 它是否知道基于某些命名约定的魔术? How does it connect this :line_items to LineItems class? 它如何将:line_items连接到LineItems类? If you could explain how these two are wired together would be great. 如果您能解释这两个如何连接在一起,那就太好了。

Yes, it's 'Rails magic' at work. 是的,它正在发挥作用。 When you define an association (in this case by using belongs_to and has_many , Rails creates a bunch of methods based on the names of the associated objects. Thus, in this case, the Product has a method .line_items added to it, which returns a Relation (basically an object that represents a database query). When the code does something with that Relation, it executes the query and returns an array of LineItem objects. 定义关联时(在这种情况下,通过使用belongs_tohas_many ,Rails基于关联对象的名称创建一堆方法。因此,在这种情况下,产品中添加了.line_items方法,该方法返回一个Relation(基本上是一个代表数据库查询的对象),当代码使用该Relation执行某些操作时,它将执行查询并返回LineItem对象的数组。

This is also the reason that Rails knows what you mean when you do things like assign associated objects ( @line_item.product = Product.find(3) ) or create new associated objects ( @product.create_line_item(:title => 'foo') ). 这也是Rails知道您执行诸如分配关联对象( @line_item.product = Product.find(3) )之类的事情或创建新的关联对象( @product.create_line_item(:title => 'foo') )。

This guide gives the details, including lists of the methods created by the various kinds of associations. 本指南提供了详细信息,包括由各种关联创建的方法的列表。

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

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