Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top