Search code examples
ruby-on-railsvalidationuniquehas-many

Unique record among x number of objects in a has_many association


I have the following models

class Acceptance < ActiveRecord::Base
  belongs_to :user
  belongs_to :requested_favor
  belongs_to :offered_favor
end

and

class RequestedFavor < Favor 
  has_many :acceptances, foreign_key: 'favor_id'
end

and

class OfferedFavor < Favor
  has_many :acceptances, foreign_key: 'favor_id'
end

Multiple users can send acceptance request to a particular favor object. acceptance has a boolean accepted attribute.

What I need is when an acceptance's accepted is set to true, no other acceptance object can be set to true. Sort of a validation or uniqeness I guess. I did my best to explain the situation clearly :)

How to achieve this? Thanks a lot for your time!


Solution

  • The most basic way to approach this would be to check before you save an acceptance and make sure that the "OfferedFavor" instance it belongs to does not already have any other "accepted" acceptances. In your acceptance model, the check would look something like this:

    offered_favor.acceptances.where(accepted: true).count > 0
    

    Hope this helps!