Tiago Veloso
Tiago Veloso

Reputation: 8563

Ruby on Rails, find by two conditions

I am trying to find all values of a given model by a combination of two fields.

I have the following model:

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "url"
    t.integer  "clicks_given"
    t.integer  "clicks_received"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

and I have defined this method for the model:

  def credits
    credits = self.clicks_given - self.clicks_received
  end

I am trying to find all users above a given credits:

  @users = User.find(:all, :conditions => { "credits >= ?", -5 })

and:

  @users = User.find(:all, :conditions => { "clicks_given - clicks_received >= ?", -5 })

Fail. What should is the correct statement to to find the right users?

Upvotes: 3

Views: 5688

Answers (2)

Thilo
Thilo

Reputation: 17735

Pass the condition as an array instead of a hash:

@users = User.find(:all, :conditions => [ "clicks_given - clicks_received >= ?", -5 ])

The first version will not work since "credits" is not a database column.

EDIT:

Or in Rails 3 syntax, with your order:

@users = User.where("clicks_given - clicks_received >= ?", 5).order("clicks_given - clicks_received")

Upvotes: 3

Harry Joy
Harry Joy

Reputation: 59694

Why don't directly use -5 in condition like this:

 @users = User.find(:all, 
                    :conditions =>"clicks_given-clicks_received>=-5")

and if you have a variable in place of -5 then you can write something like this:

@users = User.find(:all, 
                   :conditions => ["clicks_given-clicks_received >= ?",-5])

Upvotes: 1

Related Questions