【问题标题】:Custom relationship similar to dependent destroy类似于依赖销毁的自定义关系
【发布时间】:2017-09-16 18:52:31
【问题描述】:
我想实现两个模型之间的某种关系。
我有 2 个模型:quiz 和 question,它们具有多对多关系。
测验模型有quiz_flag,问题模型有question_flag。
我想要发生的事情是,当 quiz_flag 更改为 true 时,每个直接相关的问题(基本上包含在 quiz 中的每个问题)也应该将 question_flag 更改为 true。
逻辑类似于dependent: :destroy,但它是我想在quiz_flag 变为真时触发的自定义函数。
但是具体要怎么做呢?
【问题讨论】:
标签:
ruby-on-rails
ruby
web
model-view-controller
【解决方案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
我会提醒你使用回调。它可能会导致一些杂乱无章的代码,以后很难测试。
【解决方案2】:
您可以在模型中使用回调 :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