SQL查询到ActiveRecord查询

时间:2013-08-12 05:41:54

标签: ruby-on-rails-3 activerecord

如何将其转换为有效的记录查询?

select quantity from carts where cart_id = ? and product_id = ?

2 个答案:

答案 0 :(得分:1)

Cart.select(:quantity).where(:cart_id => cart_id, :product_id => product_id)

答案 1 :(得分:1)

如果您只对值感兴趣,而不是对象的开销感兴趣(因此您对任何Cart方法,关联等都不感兴趣),那么可以使用pluck并且性能稍好一些:

Cart.pluck(:quantity).where(:cart_id => cart_id, :product_id => product_id)