views:

120

answers:

2

I have the following code:

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

Which limits a person from "liking" a site more than one time based on a remote ip request. Essentially when someone "likes" a site, a record is created in the Likes table and I use a hidden field to request and pass their ip address to the :ip_address column in the like table. With the above code I am limiting the user to one "like" per their ip address. I would like to limit this to a certain number for instance 10.

My initial thought was do something like this:

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

But that doesn't seem to work. Is there a simple syntax here that will allow me to do such a thing?

A: 

No there is no shortcut macro.

You will need something like:

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
dasil003
Ok, so I just added the code your wrote above and nothing breaks which is always great out of the gate. Though, it doesn't seem to be stopping me after 10 actions.
bgadoci
I did just copy and past that code though. Did I need to edit something?
bgadoci
sorry, i just typed that off the top of my head, I haven't tested it. Try running the count query directly and see if it's working correctly
dasil003
to be honest I am not really sure what "running the count query directly" means. New to all of this.
bgadoci
A: 

You can try this:

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

Note:

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

Are you doing this to get the IP address of the client? You can get the IP address from the request object.

E.g.: In your controller/view:

request.remote_ip
KandadaBoggu
I am successfully passing the ip_address through a remote request to the like table. I just put your code in and no dice. Getting an error for 'undefined method for 'count'. Referring to 'like_count'.
bgadoci
Updated my answer, try again.
KandadaBoggu
Ah, still no go. But this is part of the same app that I am gonna give you access to. I think you will like it actually, I'm pretty satisfied w/ getting this far. Lots of fun.
bgadoci
What is the error message?
KandadaBoggu
There is no error message...just keeps letting me vote.
bgadoci
Ok...just fixed this. I had a stupid error.
bgadoci