我想在模型助手中编写一些方法并在我的视图中进行渲染。我的产品型号有价格栏。在视图中,我希望能够编写@ product.tier_one_quantity_one。如何编写帮助器以及如何渲染?
我可以在一个方法中分配多个变量吗?
module ProductsHelper
def price_variation(product)
@tier_one_quantity_one = @product.price * 1.2
@tier_one_quantity_wo = @product.price * 1.4
...
end
end
答案 0 :(得分:1)
助手采取更具功能性的方法:
module ProductsHelper
def tiered_price(product, tier, quantity)
price = case tier
when 1 then product.price * 1.2
when 2 then product.price * 1.4
else product.price * 1.6
end
price * product.quantity
end
end
# view
<%= number_to_currency( tiered_price(@product, 1, 2) ) %>
但在我看来,这在模型中会更好:
class Product < ActiveRecord::Base
def tiered_price(tier, quantity)
price = case tier
when 1 then price * 1.2
when 2 then price * 1.4
else price * 1.6
end
price * quantity
end
end
# view
<%= number_to_currency(@product.tiered_price(1, 2)) %>
如果您真的希望能够像find_by_name一样编写@ product.tier_one_quanity_two,那么您需要挂钩method_missing,这会有一些复杂性和速度开销,但会像这样:
class Product < ActiveRecord::Base
def method_missing(method, *args)
match = method.to_s.match(/tier_(.*)_quantity_(.*)/)
if match && match[0] && match[1]
unit_price = case match[0]
when 'one' then price * 1.2
when 'two' then price * 1.4
else price * 1.6
end
quantity = case match[1]
when 'one' then 1
when 'two' then 2
#.. and so on
end
unit_price * quantity
else
super
end
end
end