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