Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you validate uniqueness of a pair of ids in Ruby on Rails?

Suppose the following DB migration in Ruby:

     create_table :question_votes do |t|       t.integer :user_id       t.integer :question_id       t.integer :vote        t.timestamps     end 

Suppose further that I wish the rows in the DB contain unique (user_id, question_id) pairs. What is the right dust to put in the model to accomplish that?

validates_uniqueness_of :user_id, :question_id
seems to simply make rows unique by user id, and unique by question id, instead of unique by the pair.
like image 546
dfrankow Avatar asked May 28 '09 23:05

dfrankow


People also ask

What is validate in Ruby on Rails?

Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.

What is custom validation in rails?

Published Feb 02, 2018. Validation is one of the core features which rails provides. There are plenty of built in validation helpers there which helps validating our form inputs or user attributes.


1 Answers

validates_uniqueness_of :user_id, :scope => [:question_id] 

if you needed to include another column (or more), you can add that to the scope as well. Example:

validates_uniqueness_of :user_id, :scope => [:question_id, :some_third_column] 
like image 157
Demi Avatar answered Oct 13 '22 13:10

Demi