Rails nested attributes - does not create parent

2019-08-03 22:36发布

问题:

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.