2017-02-23 89 views
0

我有一个名为DueAction的表,它有一个DueEmployeeDetail的引用。只有当引用DueEmployeeDetail表的DueAction表的所有条目都为true时,我才需要更新DueEmployeeDetail的is_confimed列。如果有5个条目并且只有3个为真,则is_confirmed不能更新为true。在rails中查找True值

in model i have written this :- 
 

 
def is_exist(due_employee_detail) 
 
    \t # byebug 
 
    \t 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. 
 

 

 
    
 
    
 

回答

0

我假设你是舒适与您的数据库模型设计。 如果我理解得很好,则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 
+0

以及如何在控制器中访问此方法? –

+0

此方法包含在DueEmployeeDetails“生命周期”中。每当你打电话保存时,这个回调就会自动运行。 'due_employee_detail = DueEmployeeDetail.find(some_id) due_employee_detail.save' 将触发提及的逻辑 – Codextremist