嵌套属性reject_if模型有四个以上的子项

时间:2014-03-25 20:01:26

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 nested-attributes

我有以下情况:

class Question < ActiveRecord::Base
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :allow_destroy => true, :reject_if => ""

end

class Answer < ActiveRecord::Base
  belongs_to :question
end

如果一个问题的答案超过4个,我怎能拒绝创作?

1 个答案:

答案 0 :(得分:3)

我希望它适合你。

class Question < ActiveRecord::Base
  has_many :answers, :dependent => :destroy
  accepts_nested_attributes_for :answers, :reject_if => -> {|q| q['answers'].count > 4}, :allow_destroy => true
end

class Answer < ActiveRecord::Base
 belongs_to :question
end