Rails — how to populate parent object id using nested attributes for child object and strong parameters?

梦想的初衷 提交于 2019-12-02 16:13:43

So the problem you are running into is that the child objects don't pass validation, right? When the child objects are created at the same time as the parent, the child objects could not possibly know the id of their parent in order to pass validation, it's true.

Here is how you can solve that problem. Change your models as follows:

# app/models/survey.rb
class Survey
    belongs_to :user
    has_many :questions, :inverse_of => :survey
    accepts_nested_attributes_for :questions
end

# app/models/question.rb
class Question
    validates :survey, :presence => true
    belongs_to :survey
end

The differences here are the :inverse_of passed to the has_many association, and that the Question now validates on just :survey instead of :survey_id.

:inverse_of makes it so that when a child object is created or built using the association, it also receives a back-reference to the parent who created it. This seems like something that should happen automagically, but it unfortunately does not unless you specify this option.

Validating on :survey instead of on :survey_id is kind of a compromise. The validation is no longer simply checking for the existence of something non-blank in the survey_id field; it now actually checks the association for the existence of a parent object. In this case it is helpfully known due to :inverse_of, but in other cases it will actually have to load the association from the database using the id in order to validate. This also means that ids not matching anything in the database will not pass validation.

Hope that helps.

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