Search code examples
ruby-on-rails-3.1meta-wheresqueel

MetaWhere to Squeel migration


In MetaWhere I combined conditions to sql variable using loops, if else statements.

sql = {}
email_starts_with = "vany%"
sql["growth"] = 0..200
sql = sql & (:rating > 50)
sql = sql & (:email =~ email_starts_with)
.....
.....
User.where(sql).to_sql
=> "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"growth\" BETWEEN 0 AND 200 AND    \"users\".\"rating\" > 50 AND \"users\".\"email\" ILIKE 'vany%'"
user = User.where(sql).first
=> #<User id: 1, .................................. >

How can I do the same using Squeel?

Thanks for any help)


Solution

  • I resolved my problem using Arel. I think (I just changed MetaWhere code to Arel) that it is just the same as MetaWhere.

    t = User.arel_table
    
    email_starts_with = "vany%"
    sql = t[:rating].gt(50)
    sql = t[:growth].in(0..200)
    sql = sql.and(t[:email].matches(email_starts_with))
    
    User.where(sql).to_sql
    => "SELECT \"users\".* FROM \"users\"  WHERE (\"users\".\"growth\" BETWEEN 0 AND 200 AND \"users\".\"email\" ILIKE 'vany%')"
    

    Thanks everybody for help!