Validates_uniqueness_of ... limit scope - How to restrict someone from creating a certain number of records

I have the following code:

class Like < ActiveRecord::Base
  belongs_to :site
  validates_uniqueness_of :ip_address, :scope => [:site_id]
end

What deprives a person of "loving" a site more than once based on a remote ip-request. In fact, when someone “loves” the site, the record is created in the Likes table, and I use a hidden field to query and pass my IP address to the column: ip_address in a similar table. With the code above, I restrict the user to one “similar” to their IP address. I would like to limit this to a specific number, for example 10.

My initial thought was as follows:

validates_uniqueness_of :ip_address, :scope => [:site_id, :limit => 10]

But that does not work. Is there any simple syntax here that will allow me to do this?

+3
2

:

class Like < ActiveRecord::Base
  validates_each :ip_address do |row, attr, value|
    m.errors.add :ip_address, 'Too many likes' unless row.like_count < 10
  end

  def like_count
    Like.count(:conditions => {:ip_address => ip_address, :site_id => site_id})
  end
end

:

I use a hidden field to request and pass their ip address to the :ip_address 
column in the like table. 

, IP- ? IP- .

: /:

request.remote_ip
+2

.

- :

validate do |record|
  if count(:conditions => ['`id` <> ? AND `ip_address` = ? AND `site_id` = ?',
                           record.id, record.ip_address, record.site_id]) > 10
    record.errors.add(:ip_address, "has been liked the maximum number of times")
  end
end
0

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


All Articles