在以下示例中,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 %>
答案 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
方法。