Reputation: 1018
I don't know what is the proper manner to ensure that there is only one record with the same couple of foreign keys. Let's assume a class named LineItem, which belongs to an cart
and to item
. Something like:
class LineItem < ActiveRecord::Base
belongs_to :cart
belongs_to :item
The point is: I want to make unique the combination of this two "attributes". At this time, my approach was using a after_save
callback but I realized thats pretty poor. How do you resolve this? I was thinking in a PORO class (something like LineItemSaver) but I'm not completely convinced.
Thanks!
Upvotes: 1
Views: 4290
Reputation: 33542
If I understood your question correctly,you want the scope
option of the validates_uniqueness_of
. If so, this should work.
In your LineItem
model:
class LineItem < ActiveRecord::Base
belongs_to :cart
belongs_to :item
validates_uniqueness_of :cart_id, scope: :item_id
end
And also, you should be generating a migration to add this:
add_index :line_items, [ :cart_id, :item_id ], :unique => true
More Info here.
Upvotes: 5
Reputation: 3255
Try using a validate method to ensure that item_id is unique scoped to :cart_id
Something like:
validates :item_id, uniqueness: { scope: :cart_id }
Or if you want to fix the situation and simply increment the quantity you could also:
validate :ensure_line_item_uniqueness
def ensure_line_item_uniqueness
... whatever fixes the situation here ...
end
Upvotes: 2
Reputation: 16110
Can't you just do a uniqueness validation?
validates :cart_id, uniqueness: {scope: :item_id}
Upvotes: 2