有没有办法拒绝嵌套属性检查是否存在深层关联对象?现在我正在尝试这样的事情:
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
答案 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
虽然该代码段可能需要根据您应用的具体情况进行一些调整。