You can easily do this with a model check, and an index will also help. A warning, however, if you make a unique index without an accompanying ActiveRecord check, your saved data will fail and cause headaches with ease of use / debugging.
This should do it:
class Review < ActiveRecord::Base validates :user_id, :uniqueness => { :scope => :product_id, :message => "Users may only write one review per product." } end
If you want to add an index, try this in migration:
class AddUniquenessConstraintToReviews < ActiveRecord::Migration add_index :review, [:user_id, :product_id], :name => "udx_reviews_on_user_and_product", :unique => true end
Change As a full-featured Rails-dev, I still relate to ActiveRecord docs for updating the syntax of these things pretty regularly. You must too!
source share