Rails models and unique combinations

I have a Rails application that has a table called friendrequests. It looks like this:

user1_id:integer user2_id:integer hasaccepted:boolean

I create the ability to add friends, but friendrequest can only be sent once. Thus, you cannot have something like this in database data:

user1_id | user2_id | hasaccepted
       1 |        2 |       false
       1 |        2 |       false

or

user1_id | user2_id | hasaccepted
       1 |        2 |       false
       2 |        1 |       false

The combination user1_id / user2_id should be unique, not the columns themselves, so this is possible:

user1_id | user2_id | hasaccepted
       1 |        2 |       false
       1 |        3 |       false

Can this be defined in the model? How can i do this?

+3
source share
3 answers

FriendRequest validates_uniqueness_of(:user1_id, :scope => :user2_id). . #validate FriendRequest (. API docs , ).

+6

:

  validates_each :user1_id, :user2_id  do |record, attr, value|
    if FriendRequest.exists?( :user1_id => [record.user1_id, record.user2_id], 
               :user2_id => [record.user1_id, record.user2_id])
        record.errors.add attr, 'Duplicate friend request'
    end
  end
0

. , , .

, ​​ , :

  • A: ()
  • B: ()
  • A: ()
  • B: (: )
0

Source: https://habr.com/ru/post/1733397/


All Articles