简体   繁体   中英

How two classes of model are accessing each other?

Looking at a rails example with this structure for its models:

在此处输入图片说明

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:

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? 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? 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.

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') ).

This guide gives the details, including lists of the methods created by the various kinds of associations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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