问题
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:
- Validating presence of the parent object (scroll to that part).
- Issue on github
- 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