【问题标题】:How to use a scope in combination with a Model method?如何将作用域与模型方法结合使用?
【发布时间】:2011-01-04 08:32:24
【问题描述】:

我目前正在研究一些范围过滤器,我想让它过滤一个方法(不知道如何命名它)。我的代码:

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 的列?

比约恩

【问题讨论】:

    标签: ruby-on-rails ruby named-scope


    【解决方案1】:

    您不能在 :conditions 中使用 ruby​​ 方法。这不是一个专有范围的东西,它适用于所有 ActiveRecord 查询:

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

    这样做的原因是 ActiveRecord 需要的是可以“翻译”成数据库字段的东西。符号:price_with_discount 无法翻译到数据库中。

    此外,如果您在 Rails 3 上,you don't really need scopes any more。一个普通的类方法会做同样的事情,而且更容易编写(没有 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
    

    【讨论】:

    • 感谢您的解释,我将代码调整为类似于您的示例,我在 Rails 3 上,它运行良好。
    【解决方案2】:

    您不能尝试对我们的 Ruby 方法进行 SQL 限制。避免使用它,如果您的价格折扣不是字符串,我想它是有效的

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-23
      • 1970-01-01
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      相关资源
      最近更新 更多