Rails nested attributes - does not create parent

99封情书 提交于 2020-01-05 04:38:15

问题


I have the following models:

class Parent
  has_many :cars
  accepts_nested_attributes_for :cars
end

class Car
  belongs_to :parent
  validates :parent, presence: true
end

The controller code:

def create
  parent = Parent.new
  parent.attributes = parent_params
  parent.save
end

def parent_params
  params.require(:parent).permit(:name,  cars_attributes: [:name])
end

When I try to create a Parent with Cars, the validation fails on the Cars because the Parent was not created yet. How can I make it pass validations when it's being created through nested attributes?


回答1:


Based on a quick search, you could use :inverse_of to overcome this situation.

In your code:

class Parent
  has_many :cars, inverse_of: :parent
  accepts_nested_attributes_for :cars
end

class Car
  belongs_to :parent
  validates :parent, presence: true
end

(not tested)

Check out dem sources:

  1. Validating presence of the parent object (scroll to that part).
  2. Issue on github
  3. Some post I didn't bother to read but is referenced on the issue above

GL & HF.



来源:https://stackoverflow.com/questions/21239640/rails-nested-attributes-does-not-create-parent

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