zcserei
zcserei

Reputation: 665

Rails associations: something has many, but only one per other entity

I have three models. User, Application and ApplicationVote

The following are true:

  1. An ApplicationVote belongs to both a User and an Application.
  2. A User can cast a vote on an Application, thus creating an ApplicationVote
  3. A user can vote on any number of applications, but can only have one vote per application.

If there would be a way to say User has_many ApplicationVotes but only one per Application... what would it look like?

Upvotes: 0

Views: 41

Answers (1)

Ursus
Ursus

Reputation: 30056

Something like this

application level, into the application_vote.rb model file

validates_uniqueness_of :application_id, scope: :user_id

database level, in a migration file

add_index :application_votes, [:user_id, :application_id], unique: true

Upvotes: 3

Related Questions