如何将范围与模型方法结合使用?
我目前正在研究一些范围过滤器,我想让它过滤一个方法(不知道如何命名它)。我的代码:
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
这不起作用:“表 products
不存在名为 price_with_discount
的属性”。如何欺骗我的范围使用我定义的方法而不是搜索名为 price_with_discount
的列?
比约恩
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能在
:conditions
中使用 ruby 方法。这不是一个排他范围的事情,它适用于所有 ActiveRecord 查询:原因是 ActiveRecord 需要的是可以“翻译”到数据库字段的东西。符号
:price_with_discount
无法转换到数据库。此外,如果您使用的是 Rails 3,您实际上并不不再需要范围。常规类方法会执行相同的操作,并且更容易编写(没有 lambda)。
You can't use ruby methods inside
:conditions
. This is not an exclusive scope thing, it applies in all ActiveRecord queries: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).
您不能尝试对我们的 Ruby 方法进行 SQL 限制。避免使用它,我想如果你的价格折扣不是字符串,它是有效的
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