01 January 2017

Rails - restrict user from entering more than one record per association

Thumb 709578 1280x800  desktopnexus.com
Anee Syed
Drupal Developer

We can Easily do this with a model validation, and an index would help as well. Warning though, if you do the unique index without the accompanying ActiveRecord validation your saves will fail silently and cause a usability/debugging headache.#Rails

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 the index, try this in a migration:

class AddUniquenessConstraintToReviews < ActiveRecord::Migration
  add_index  :review, [:user_id, :product_id],
    :name => "udx_reviews_on_user_and_product", :unique => true
end

the ActiveRecord docs for refreshers on the syntax of these things pretty regularly. You should too!

Let's make something great together

Get in touch with us and send some basic info for a quick quote