【问题标题】:Model helper in rails and render in the viewRails 中的模型助手并在视图中渲染
【发布时间】:2011-11-01 18:30:44
【问题描述】:

我想在模型助手中编写一些方法并在我的视图中渲染。我的产品型号有价格列。例如,在视图中,我希望能够编写 @product.tier_one_quantity_one。 helper怎么写,怎么渲染?

我可以在一个方法中分配多个变量吗?

module ProductsHelper
  def price_variation(product)
    @tier_one_quantity_one = @product.price * 1.2
    @tier_one_quantity_wo = @product.price * 1.4
    ...
  end
end

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 感谢您的回复,但我需要为每个产品呈现多个价格变化,而不是从各种场景中获得正确的价格。这些变化是从 product.price 列中计算出来的
    • 其实我需要做的是tier_three_quantity_one = product.price。 tier_three_quantity_two = tier_three_quantity_one * (1- VOLUME) where VOLUME = 0.02 与第 4 层相同 Tier_four_quantity_one = product.price * (1 + PERCENTAGE) where PERCENTAGE = 0.2
    猜你喜欢
    • 2015-11-16
    • 2011-03-20
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2012-07-21
    • 2015-07-16
    相关资源
    最近更新 更多