If I have:
class Product < ActiveRecord::Base
has_many :product_attributes
end
class ProductAttribute < ActiveRecord::Base
belongs_to :product
validates_uniqueness_of :position, :scope => [:product_id]
end
Now if I create a new Product record including 2 ProductAttributes with the same value for the "position" field, it will "validate and save".
However, the 2nd ProductAttribute will not actually be saved and there are not any validation errors thrown.
Here is some console action to demonstrate:
p = Product.new(:MPN => "324234", :name => "good", :weight => "32", :manufacturer_id => "0", :short_description => "b", :long_description => "b", :UPC => "23423423", :SKU => "asf232")
>> pa = ProductAttribute.new(:position => 1, :key => "b", :value => "b", :value_unit_id => "1", :value_type_id=>"1", :value_array => "false")
>> pa.product = p
>> p.product_attributes << pa
>> p.product_attributes << pa #2nd attribute with same position value
>> p.valid?
=> true
>> p.save
=> true
>> p.product_attributes.count
=> 1
I'm assuming this has something to do with :product_id being nil in the associated records. How can I save this all in one shot and have proper validation?