Forum: Ruby on Rails Validations on parent and accepts_nested_attributes_for don't comply?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ronald Wind (Guest)
on 2009-03-10 17:07
(Received via mailing list)
Hello,

I've got two models:

class ProductGroup < ActiveRecord::Base
   has_many :fields, :dependent => :destroy
   accepts_nested_attributes_for :fields
end

class Field < ActiveRecord::Base
   belongs_to :product_group
   validates_presence_of :product_group
end


Now when I try something like this:
ProductGroup.create(:title => "foo", :fields_attributes => {"new_1" =>
{:title => "bar"}})
it'll fail because of the validates_presence_of :product_group
validation. Since the field is being build by the
product_group.fields.build function (in
assign_nested_attributes_for_collection_association of the
NestedAttributes module) the product reference of field is not set
because the ProductGroup instance is not saved yet, and hence the
validation fails.

Now if I remove the validation all goes well and both objects are saved
as they should.

Is there a better / other way to make sure a Field can only be saved
when it has a reference to a ProductGroup while still being able to use
the nested attributes functionality?

Thanks,

Ronald
This topic is locked and can not be replied to.