activerecord-hackery / squeel

Active Record, improved. Live again :)
http://erniemiller.org/2013/11/17/anyone-interested-in-activerecord-hackery/
MIT License
2.4k stars 213 forks source link

Squeel ambiguously ignoring where condition #353

Closed mhuggins closed 9 years ago

mhuggins commented 9 years ago

I'm trying to write a query based upon an account_id column on a model. (Note that this is not an ID utilized for a belongs_to relationship; it is simply a custom generated string that is meant to tell users "this is your account number".) Unfortunately, this one column is being ignored by squeel as seen below.

pry(main)> User.where{account_id != nil}.count
   (0.5ms)  SELECT COUNT(*) FROM "users"
=> 313
pry(main)> User.where{account_id == nil}.count
   (0.6ms)  SELECT COUNT(*) FROM "users"  WHERE ('t')
=> 313
pry(main)> User.where{email != nil}.count
   (0.6ms)  SELECT COUNT(*) FROM "users"  WHERE "users"."email" IS NOT NULL
=> 313
pry(main)> User.where{mongo_id != nil}.count
   (0.6ms)  SELECT COUNT(*) FROM "users"  WHERE "users"."mongo_id" IS NOT NULL
=> 313

I included the mongo_id example above to show another similar column that is also a custom value, not intended for a join. In that example, the query produced matches expectations.

For reference, here's my table definition:

create_table :users do |t|
  t.string :mongo_id, null: false
  t.string :email, null: false, default: ''
  t.string :account_id
  # ...snip...
end

add_index :users, :mongo_id, unique: true
add_index :users, :email, unique: true
add_index :users, :account_id, unique: true

Additionally, here's some manual testing in Rails console to ensure the attribute is properly defined on the ActiveModel class:

pry(main)> User.attribute_names.include?('account_id')
=> true
pry(main)> User.attribute_names.include?('mongo_id')
=> true

Any help is appreciated!

mhuggins commented 9 years ago

Ahh, I (partially) figured it out. I have a variable in the same context named account_id. Should I be using my{account_id} for the query instead?

User.where{my{account_id} != nil}.count
mhuggins commented 9 years ago

Alright, I got it. Looks like I can pass a param to reference:

User.where{ |u| u.account_id != nil}.count