Rails:如何从返回的对象访问范围?

时间:2011-07-29 16:59:34

标签: ruby-on-rails ruby-on-rails-3

在以下示例中,amount_below_limit实例方法如何访问max_weight范围的参数?

# Model
class Elephant < ActiveRecord::Base
  scope :max_weight, lambda { |limit| where('weight <= ?', limit) }

  def amount_below_limit
    max_weight = # How can I see 1000 from here?
    max_weight - weight
  end
end

# Controller
@elephants = Elephant.max_weight(1000)

# View
<% @elephants.each do |elephant| %>
  <%= elephant.amount_below_limit %>
<% end %>

3 个答案:

答案 0 :(得分:0)

您可以在sql中执行此操作:

class Elephant < ActiveRecord::Base
  scope :max_weight, lambda { |limit| where('weight <= ?', limit).
                                      select("elephants.*, #{limit}-weight as amount_below_limit") }
  def amount_below_limit
    read_attribute(:amount_below_limit) || -1
  end
end

答案 1 :(得分:0)

限制范围为块。它不存在于lambda之外

答案 2 :(得分:0)

感谢您的建议。

最后,我重构了我的代码,使参数变为max_weight一个实例变量,然后我将其传递给amount_below_weight方法。