Rails接受嵌套属性:如果关联具有空白关联项,则拒绝

时间:2017-01-30 19:10:06

标签: ruby-on-rails ruby

有没有办法拒绝嵌套属性检查是否存在深层关联对象?现在我正在尝试这样的事情:

class Submission < ApplicationRecord
  has_many :answers, dependent: :destroy
  accepts_nested_attributes_for :answers, reject_if: :has_answer?

  # REJECT ANSWER IF ASSOCIATED ANSWER TYPE IS BLANK
  def has_answer?
    answers.each do |a|
      a.answer_open.present? || a.answer_rating.present?
    end
  end
end

class Answer < ApplicationRecord
  has_one :answer_open, dependent: :destroy
  has_one :answer_rating, dependent: :destroy

  accepts_nested_attributes_for :answer_open, reject_if: proc { |a| a['response'].blank? }
  accepts_nested_attributes_for :answer_rating, reject_if: proc { |a| a['response'].blank? }
end

2 个答案:

答案 0 :(得分:0)

self.answers.each do应该{{1}}对吗?

答案 1 :(得分:0)

你离得太远了。根据{{​​3}},reject_if选项在这里是正确的。

但是,您的has_answer?方法正在检查已与提交相关联的答案您应该检查answers_attributes的值。在上面的链接中使用posts_attributes查找示例。其中一个使用reject_if检查嵌套属性。

此外,您的has_answer?方法返回一个数组,该数组始终为true。你可能想要这样的东西:

attributes['answers_attributes'].any? do |a|
  a['answer_open'].present? || a['answer_rating'].present?
end

虽然该代码段可能需要根据您应用的具体情况进行一些调整。