2

I was reading the book of Dave Thomas, "Agile Web Development with Rails", Fourth Edition. Inside a class named Cart, he called an attribute named "line_items" provided by a relationship between the classes Cart and LineItem.

Inside the method that uses this attribute int the Cart class, the attribute is called without the "@" that is used when we invoke the attributes of a instance. Can someone say to me why this work? Because I was expecting that he had used the "@" symbol. The code is shown below:

class Cart < ActiveRecord::Base
 has_many :line_items, :dependent => :destroy
 def add_product(product_id)
 #In this line below, I was expecting @lineitems.find_by ..... 
  current_item = line_items.find_by_product_id(product_id)
  if current_item
   current_item.quantity += 1
  else
   current_item = line_items.build(:product_id => product_id)
  end
  current_item
 end 
end
4

1 回答 1

4

之所以有效,是因为为 --has_many创建了一个读取器和写入器方法,line_items其方式类似于 usingattr_accessor为该属性名称创建读取器和写入器方法。它与以下内容非常相似:

class Cart
  def line_items
    @line_items
  end

  def line_items=(value)
    @line_items = value
  end
end

Rails 为您创建了许多这样的方法,包括针对您正在使用的模型的数据库的每一列的方法,以及针对所有关联的方法(例如line_items这里)。

有关为特定关联添加哪些方法的详细信息,请参阅 Rails 指南中“Active Record 关联指南”的第 4 章。

于 2012-11-30T02:49:00.253 回答