ActiveRecord::Relation对象

在Rails Console中使用where语句查询后得到的是Relation对象, 要想获取最终的对象,需要在后面加上first方法。

查询得到的是ActiveRecord::Relation

@cart = Cart.where(product_id: 2, user_id: 2)
2.4.0 :081 > Cart.where(product_id: 2, user_id: 2)
  Cart Load (0.3ms)  SELECT "carts".* FROM "carts" WHERE "carts"."product_id" = $1 AND "carts"."user_id" = $2  [["product_id", 2], ["user_id", 2]]
 => #<ActiveRecord::Relation [#<Cart id: 196, user_id: 2, product_id: 2, amount: 0.11e2, created_at: "2017-02-20 07:26:05", updated_at: "2017-02-20 07:52:36">]>

查询得到的是Object

@cart = Cart.where(product_id: 2, user_id: 2).first
2.4.0 :080 >   @cart = Cart.where(product_id: 2, user_id: 2).first
  Cart Load (0.4ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."product_id" = $1 AND "carts"."user_id" = $2 ORDER BY "carts"."id" ASC LIMIT $3  [["product_id", 2], ["user_id", 2], ["LIMIT", 1]]
 => #<Cart id: 196, user_id: 2, product_id: 2, amount: 0.11e2, created_at: "2017-02-20 07:26:05", updated_at: "2017-02-20 07:52:36">
Category.where(:id => 1)
# Is Equivalent to Category.all(:conditions => {:id => 1}})
Category.where(:id => 1).first
# Is equivalent of Category.first(:conditions => {:id => 1}})

Resources

相关文章: