In Rails, how do I create nested objects using accepts_nested_attributes_for?

帅比萌擦擦* 提交于 2019-12-04 20:14:10

All right, I found the solution to my problem. All I need to do is validate the presence of training_class instead of class_id in the ClassMeeting model. That way the existence of a training class is still validated, but the validator doesn't interfere with accepts_nested_attributes_for's method of saving the model:

class ClassMeeting < ActiveRecord::Base
  attr_accessible :start, :end, :location

  validates :training_class, presence: true # :training_class instead of :class_id
  validates :start, presence: true
  validates :end, presence: true
  validates :location, presence: true, length: {maximum: 255}

  belongs_to :training_class, foreign_key: :class_id, inverse_of: :meetings
end
monozok

I pored over this example, trying out the differences with my code, but in the end my problem was fixed by using :inverse_of.

See accepts_nested_attributes_for child association validation failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!