accepts_nested_attributes_for child association validation failing

后端 未结 6 2051
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 07:02

I\'m using accepts_nested_attributes_for in one of my Rails models, and I want to save the children after creating the parent.

The form works perfectly, but the vali

6条回答
  •  一生所求
    2020-12-02 07:47

    Only validate the relationship, not the ID:

    class Task < ActiveRecord::Base
      belongs_to :project
    
      validates_presence_of :project
    end
    

    As soon as the association is populated, ActiveRecord will consider the validation to have succeeded, whether or not the model is saved. You might want to investigate autosaving as well, to ensure the task's project is always saved:

    class Task < ActiveRecord::Base
      belongs_to :project, :autosave => true
    
      validates_presence_of :project
    end
    

提交回复
热议问题