【问题标题】:Providing prizes depending on user_plan and duration_days根据 user_plan 和 duration_days 提供奖品
【发布时间】:2020-05-22 07:31:20
【问题描述】:

对于一日游,我们有这个助手可以根据用户的计划完美地提供奖品。

  def cost_inscription
    if user_signed_in?
      case current_user.plan_id
      when 1 
        6
      when 2 
        3
      when 3 
        1
      end 
     else
        16
    end
  end

目前我们有一个用户计划和旅程持续时间的奖励表 (3x5):1,2,3,4 o+ 天。 如何获取提供两个变量的铭文成本:user_plan 和旅程天数。

确定你有一个好帮手!让我知道,提前谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby conditional-statements


    【解决方案1】:

    建立一个描述奖品的常量散列。这里的持续时间是一个关键并且计划存储为hashes with a default value

    PRIZES = {
      1 => {1 => 6, 2 => 3, 3 => 1}.tap { |h| h.default = 16 },
      2 => {1 => 6, 2 => 3, 3 => 1}.tap { |h| h.default = 14 },
      3 => {1 => 6, 2 => 3, 3 => 1}.tap { |h| h.default = 12 },
      4 => {1 => 6, 2 => 3, 3 => 1}.tap { |h| h.default = 10 },
      5 => {1 => 6, 2 => 3, 3 => 1}.tap { |h| h.default = 8 }
    }.freeze
    
    def cost_inscription(duration, plan)
      PRIZES[duration][plan]
    end
    

    【讨论】:

    • 我们在两个表 PRODUCTS { duration, Prize, ... } 和 JOURNEY { duration, } 中有这个值,我们也可以得到 current_user 的 plan_id。可以提供这两个变量(持续时间、计划)以获得相应的 PRIZE。我需要更多帮助来拆分这是帮助器、控制器和视图。
    • 我不确定我是否遵循。您有 cost_inscription 方法,它基于一个参数返回一个整数。我提供了相同的方法,重写后基于两个参数返回一个整数。这与助手、控制器、视图和其他 Rails 废话有什么关系?
    • 感谢您的帮助。我希望现在更清楚我在寻找什么,例如双重 CASE/WHEN 方法。因为不要重复 if 语句。
    【解决方案2】:

    帮手

    def inscription_pd_id(ndays)
    if user_signed_in? && current_user.plan_id == 0 #SIMPATITZANT
      case ndays
      when 1
        4  
      when 2 
        8
      when 3 
        12
      when 4 
        16
      when 5 
        20        
      end
    end
    if user_signed_in? && current_user.plan_id == 1 #ESPORÀDIC
      case ndays
      when 1
        5  
      when 2 
        9
      when 3 
        13
      when 4 
        17
      when 5 
        21        
      end
    end
    if user_signed_in? && current_user.plan_id == 2 #FREQÜENT
      case ndays
      when 1
        6  
      when 2 
        10
      when 3 
        14
      when 4 
        18
      when 5 
        22        
      end
    end
    if user_signed_in? && current_user.plan_id == 3 #HABITUAL
      case ndays
      when 1
        7  
      when 2 
        11
      when 3 
        15
      when 4 
        19
      when 5 
        23        
      end
    end
      end
    

    控制器

      def show
    
        @sortide = Sortide.friendly.find(params[:id])
    
        @product = Product.find(helpers.inscription_pd_id(@sortide.ndays).to_i) 
    
         end
    

    查看

    <%= @sortide.ndays %>
    <%= current_user.plan_id %>
    <%= @product.prize %>
    

    我知道这并不了不起,但它确实有效。 寻找更清洁/更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-19
      • 2017-10-19
      相关资源
      最近更新 更多