2017-09-16 50 views
1

我想实现2个模型之间的某种关系。自定义关系类似于dependent destroy

我有2个型号:quizquestion有多对多的关系。 测验模型有quiz_flag和问题模型有question_flag

我希望发生的事情是什么时,quiz_flag更改为真,每一个问题,那就是在直接关系(基本上是一个被包含在quiz内的每一个问题),也应该改变question_flag为true。

逻辑与dependent: :destroy类似,但它是一个自定义函数,当quiz_flag为真时,我想触发它​​。 但我该怎么做呢?

回答

1

您可以在模型中使用回调:before_update。 我会做这样的事情:

class Quiz < ApplicationRecord 
before_update :update_question_flags, :if => :question_flag_changed? 

    def update_question_flags 
    self.questons.update_all(question_flag:true) 
    end 
end 
1

只需要添加额外的逻辑,以任何形式/行动负责设置测验。

即:

if params[:quiz_flag] #if the quiz_flag params is set to true. 
    @quiz.questions.update_all(question_flag: true) 
end 

或者,如果它是多个控制器,你可以使用回调:

测验型号:

before_save :some_method #will work before object is saved 

(既创建和更新工作,如果你只是想更新使用before_update)

def some method 
if self.quiz_flag == true 
    self.questons.update_all(question_flag:true) 
end 
end 

虽然我会提醒你使用回调。它可能会导致一些杂乱的代码,以后很难再测试。

相关问题