【问题标题】:Finding True value in rails在 Rails 中找到真正的价值
【发布时间】:2017-02-23 08:24:40
【问题描述】:

我有一个名为 DueAction 的表,它有一个 DueEmployeeDetail 的引用。我需要更新 DueEmployeeDetail 的 is_confimed 列,只有当 DueAction 表的所有条目都引用 DueEmployeeDetail 表时为真。例如。如果有 5 个条目且只有 3 个为 true,则 is_confirmed 不得更新为 true。

in model i have written this :-

def is_exist(due_employee_detail)
  	# byebug
  	flag = 0
    DueAction.exists?(is_confirm: true,due_employee_detail_id: due_employee_detail)
    flag
  end

in controller i have wriien this:-

  if @due_action.is_exist(@due_action.due_employee_detail_id)
  DueEmployeeDetail.where(id: @due_action.due_employee_detail_id).update_all(is_confirmed: true)
  else
  end
  
  but its not working.Its checking only true not checking whether all are true or not.


  
  
  

【问题讨论】:

    标签: ruby-on-rails-4 rails-activerecord


    【解决方案1】:

    我假设您对自己的数据库模型设计感到满意。 如果我理解得很好,DueAction 有一个 DueEmployeeDetail 的引用。你最好不要在你的控制器中这样做,你可以把这个逻辑移到你的模型中。

    class DueEmployeeDetail < ActiveRecord::Base
    
      before_save :confirm!, if: :has_all_due_actions_confirmed?
    
      def has_all_due_actions_confirmed?
        due_actions.all?(&:is_confirmed)
      end
    
      def confirm!
        self.is_confirmed = true
      end
    
    
    end
    

    【讨论】:

    • 我如何在控制器中访问这个方法??
    • 此方法包含在 DueEmployeeDetails“生命周期”中。每当您对其调用 save 时,此回调将自动运行。 due_employee_detail = DueEmployeeDetail.find(some_id) due_employee_detail.save 将触发上述逻辑
    猜你喜欢
    • 2022-01-22
    • 1970-01-01
    • 2021-07-10
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-31
    • 1970-01-01
    相关资源
    最近更新 更多