我完全误解了rails中的机制......想象一个具有许多属性的产品模型:
class Product < ActiveRecord::Base
has_many :properties
end
然后,在控制台中,我输入:
p=Product.last #recover the last product created
arr=p.properties #return the properties in an Array
arr.class #return "Array", so it's effectively an Array object.
在 Hirb 中,它给了我:
1.9.3-p385 :161 > arr=p.properties
| id | name | presentation | created_at | updated_at | value_type |
+-----------+-------------+---------------+-------------------------+-------------------------+------------+
| 905834907 | internet | internet | 2012-09-17 13:37:57 UTC | 2012-10-02 15:46:37 UTC | boolean |
| 905834906 | three_d | 3D | 2012-09-17 13:37:47 UTC | 2012-10-10 13:10:07 UTC | boolean |
| 161337574 | brand | Marque | 2012-05-22 14:13:04 UTC | 2013-03-26 16:12:12 UTC | string |
ETC...
然后,如果我这样做:
1.9.3-p385 :162 > arr.where(:value_type => "boolean")
Spree::Property Load (0.8ms) SELECT "spree_properties".* FROM "spree_properties" INNER JOIN "spree_product_properties" ON "spree_properties"."id" = "spree_product_properties"."property_id" WHERE "spree_product_properties"."product_id" = 1060500665 AND "spree_properties"."value_type" = 'boolean'
+-----------+----------+--------------+-------------------------+-------------------------+------------+
| id | name | presentation | created_at | updated_at | value_type |
+-----------+----------+--------------+-------------------------+-------------------------+------------+
| 905834907 | internet | internet | 2012-09-17 13:37:57 UTC | 2012-10-02 15:46:37 UTC | boolean |
| 905834906 | three_d | 3D | 2012-09-17 13:37:47 UTC | 2012-10-10 13:10:07 UTC | boolean |
| 905834914 | wifi | wifi | 2013-03-26 16:13:35 UTC | 2013-03-26 16:13:35 UTC | boolean |
所以我在数组上运行 where 方法......但是:
tab.method(:where) #returns:
NameError: undefined method `where' for class `Array'
如何在无法识别的对象上执行 where ?我有个想法:
1.9.3-p385 :164 > arr.klass
=> Spree::Property(id: integer, name: string, presentation: string, created_at: datetime, updated_at: datetime, value_type: string)
但我真的不明白这种机制......这对我来说在面向对象的语言中是全新的。
谢谢你的解释。
酸碱度