简化或改进方法

时间:2017-06-07 09:51:36

标签: ruby-on-rails ruby

在保存模型之前执行以下代码。它会在循环之前检查has_many关联以进行更改,并在每个关联上设置值。它会检查每个答案选项是否在任何答案上更改了correct_answer。如果是这样,它会查找哪些已更改且为true

if self.answer_options.select{|a| a.correct_answer_changed?}.any?
  self.answer_options.each do |answer_option|
    if answer_option.correct_answer_changed? && !answer_option.correct_answer_was
      answer_option.correct_answer = true
    else
      answer_option.correct_answer = false
    end
  end
end

我如何简化或改进此方法?

2 个答案:

答案 0 :(得分:1)

假设您共享的代码正在运行,我会把它干掉一点......

self.answer_options.map{|a| a if a.correct_answer_changed?}.compact.each do |answer_option|
  answer_option.toggle(:correct_answer)
end

答案 1 :(得分:0)

answer_options.each do |answer_option|
  answer_option.correct_answer =
    answer_option.correct_answer_changed? && !answer_option.correct_answer_was
end
if answer_options.all?{|answer_option| answer_option.correct_answer == false}
  answer_options.each{|answer_option| answer_option.correct_answer == nil}
end