开发者

How to use a scope in combination with a Model method?

I'm currently working on some scope filters, and I'd like to have it filter on a method (don't know how to name it otherwise). My code:

class Product < ActiveRecord::Base
 开发者_运维百科 def price_with_discount
    price-discount.to_f
  end

  scope :by_price, lambda {|min,max|{ :conditions => { :price_with_discount => min.to_f..max.to_f }}}
end

This doesn't work: "No attribute named price_with_discount exists for table products". How can I trick my scope into using the method I defined instead of searching for a column named price_with_discount?

Bjorn


You can't use ruby methods inside :conditions. This is not an exclusive scope thing, it applies in all ActiveRecord queries:

# This won't work either
Product.where(:price_with_discount => min.to_f)

The reason for this is that what ActiveRecord needs is something that can be "translated" into database fields. The symbol :price_with_discount can not be translated to the database.

Besides, if you are on rails 3, you don't really need scopes any more. A regular class method will do the same, and it's easier to write (no lambdas).

class Product < ActiveRecord::Base
  def self.by_price(min, max)
    # Assuming that products.discount is a database field:
    where([ "(products.price - products.discount) >= ? AND " +
            "(products.price - products.discount) <= ?",
            min, max
    ])
  end
end


You can't try to do a SQL restriction on our Ruby method. Avoid using it and I suppose it's works if your price-discount is not a String

scope :by_price, lambda {|min,max|{ :conditions => { :price-discount => min.to_f..max.to_f }}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜