aidiah aidiah - 2 years ago 42
Ruby Question

Getting unexpected ',', expecting => ban error

why am I getting the error:

`syntax error, unexpected ',', expecting => ban = Ban.where(:banned => 1, expires < ?", current_time) ^

Extracted source (around line #7):`

I also get the error:

undefined method 'expires' for #<Ban::ActiveRecord_Relation
if I remove the
:banned => 1,

class Ban < ActiveRecord::Base
before_create :unban
def unban
puts "starting unban"
current_time =
puts current_time
ban = Ban.where(:banned => 1, "expires < ?", current_time)
if current_time > ban.expires
ban.update_attributes(:banned => 0)
puts "worked"

Answer Source

You've intermingled where clause condition types; one is hash conditions, and the other using replacement parameters. You can go with the shorter approach, which uses a single string, like this:

ban = Ban.where("banned = 1 and expires < ?", current_time)

or separately, like this:

ban = Ban.where(banned: 1).where("expires < ?", current_time)

The query will retrieve multiple answers, so you can't directly access a single record. This is why you get the error with expires. You should also verify that the query has returned a record before trying to use data from it. You can either try this:

if ban.length > 0 && current_time > ban.first.expires

or change the result of the query and the if statement to this:

ban = Ban.where("banned = 1 and expires < ?", current_time).first
if ban && current_time > ban.expires
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download