Rails 类方法和对象方法分不清,求助

jiffies · 2012年03月28日 · 最后由 chentianwen 回复于 2012年03月29日 · 4301 次阅读

在 agile rails 书中有这样一段代码 m

class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy
  def add_product(product_id)
    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

请问这里的 line_items 应该是当前调用 cart 对象的 line_item 数组吧,它也能调用 find 的函数? 不是应该 LineItem 类调用的嘛?

正好我可以帮到你。因为我也在看这本书。

line_items 才不是什么 cart 对象的数组。他是 cart 的一个属性,这个属性通过 has_many 定义. 也就是常说的外键。通过这个属性,获取到了 line_items 对象,现在你明白了吧?

line_items 是动态方法,这里的调用相当于 self.line_items,内部其实是 sql 语句: select "line_items".* from where ........什么的 加上 find_by_product_id 其实是组合 sql 语句,为前面那个查询添加条件而已。

#2 楼 @zw963 我知道,这个方法返回一个数组嘛。书上没说过自动增加的 collection 的几个方法吧

#1 楼 @cqpx 谢谢,就是这个问题

1 楼已经说清楚了呀:

4.3.1 Methods Added by has_many

When you declare a has_many association, the declaring class automatically gains 13 methods related to the association:

collection(force_reload = false) collection<<(object, …) collection.delete(object, …) collection=objects collection_singular_ids collection_singular_ids=ids collection.clear collection.empty? collection.size collection.find(…) collection.where(…) collection.exists?(…) collection.build(attributes = {}, …) collection.create(attributes = {})

#6 楼 @zeeler 对的对的,还是 rails guide 更细致点

#3 楼 @adventurelw self 有点分不清

class Order
  def self.foo
    self.find
    find
  end
哪些是调用Order类的,哪些是该类的实例呢? 

#8 楼 @jiffies self 是一个相对的变量。

以下代码中 self 是,Order 对象 (注意 不是 Order 类的对象)

class Order def self.foo end end

以下代码中 self 是,Order 类的对象

class Order def foo self.find end end

难点在于,Order 即是类,又是对象,Order 是 Class 类的对象。 还有一种理解方式, Order 是一个变量,变量的类型是 Class。

#10 楼 @ery 第二种,Order 类的对象那个 self 可以省略是嘛?这里 find 默认是实例方法? ps:难道你也在看欧冠?

#11 楼 @jiffies 1 可以省略,但前提是 find 方法不是 private 方法 2 起床上班

lineitems 是 activerecord 里面的 Assiciations 实例,可以调用类似 scope 的方法,但这个是实例方法。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号