我在rails控制台中使用数据来测试一些关系,它似乎只输出数组的第一条记录。
我有一个名为c
的变量,它是我项目中Comparison
类的一个实例。
我建立了关系,所以我可以调用c.products,它会返回一个比较中所有产品的数组,在这种情况下是2。
问题出在我打电话的时候:
c.products
它只返回2中的第一个产品。
c.products[1]
返回nil。
y c.products
相同数据的更详细版本显示了这两种产品。
c.products.count
返回2.
以下是rails c中的内容:
c.products
=> [#<Product id: 1, category_id: 3, name: "Camera", description: "erererer", brand: "Canon", quantity: 3, star_rating: 4, price: 299.0, created_at: "2014-06-18 20:26:34", updated_at: "2014-06-19 06:40:34">]
c.products.count
(0.5ms) SELECT COUNT(*) FROM "products" INNER JOIN "compared_products" ON "products"."id" = "compared_products"."product_id" WHERE "compared_products"."comparison_id" = $1 [["comparison_id", 2]]
=> 2
和y c.products将其缩小为仅显示最后一个产品,因为它返回了大量数据。
y c.products
--- &10 !ruby/object:ActiveRecord::Associations::CollectionProxy
association: !ruby/object:ActiveRecord::Associations::HasManyThroughAssociation
reflection: &1 !ruby/object:ActiveRecord::Reflection::ThroughReflection
macro: :has_many
name: :products
scope:
options:
:through: :compared_products
active_record: &2 !ruby/class 'Comparison'
klass: &3 !ruby/class 'Product'
plural_name: products
collection: true
automatic_inverse_of: false
type:
foreign_type: products_type
constructable: true
source_reflection_name: :product
class_name: Product
chain:
- *1
- !ruby/object:ActiveRecord::Reflection::AssociationReflection
macro: :has_many
name: :compared_products
scope:
options: {}
active_record: *2
klass: !ruby/class 'ComparedProduct'
plural_name: compared_products
collection: true
automatic_inverse_of:
type:
foreign_type: compared_products_type
constructable: true
class_name: ComparedProduct
foreign_key: comparison_id
active_record_primary_key: id
scope_chain:
- []
- []
owner: !ruby/object:Comparison
attributes:
id: 2
user_id: 1
name: Jacks Electronics Comparison
created_at: 2014-06-20 16:12:36.828154000 Z
updated_at: 2014-06-20 16:12:36.828154000 Z
loaded: true
target:
- !ruby/object:Product
attributes:
id: 1
category_id: 3
name: Camera
description: erererer
brand: Canon
quantity: 3
star_rating: 4
price: 299.0
created_at: 2014-06-18 20:26:34.276570000 Z
updated_at: 2014-06-19 06:40:34.776216000 Z
答案 0 :(得分:2)
正如您所看到的,c.products
未触发sql查询,这意味着它已被缓存。另一方面,c.products.count
触发查询并告诉您来自数据库的实际信息。因此,您的c.products
可能通过其他关联或直接在数据库中手动更改。要接收实际产品c.products.reload
,要计算缓存产品(没有sql触发),请执行c.products.size
请参阅此处的详细说明https://stackoverflow.com/a/18997294