felix
felix

Reputation: 11542

Ruby on Rails question regarding scope

I have the following named scope in my model

class User
  scope :single_action, where("parent_id = ?", nil)
end

Even though there are records with parent_id with nil values, they do not seem to be available.

ruby-1.9.2-p0 > User.select("name")
 => [#<User parent_id: nil, name: "John">, #<Task parent_id: 1, name: "Felix">, #<Task parent_id: nil, name: "John Felix">]

I tried using the active record query to do the same, but it also returns empty resultset

ruby-1.9.2-p0 > User.where("parent_id = ?",nil)
 => []

I have defined few other scopes which seems to be working fine. My Rails version is 3.0.7 and Ruby version is Ruby 1.9.2 Could you please help me to solve this problem.

Thanks :)

Upvotes: 0

Views: 524

Answers (1)

Spyros
Spyros

Reputation: 48626

Change that to :

User.where(:parent_id => nil)

You can see the difference (you were actually trying to match the string 'NULL' instead of checking for the value being NULL):

ruby-1.9.2-p180 :031 > User.where("remember_token = ?", nil)
 => [] 
ruby-1.9.2-p180 :032 > User.where(:remember_token => nil)
 => [#<User id: 232255501, .......

ruby-1.9.2-p180 :029 > User.where(:remember_token => nil).to_sql
 => "SELECT `users`.* FROM `users` WHERE (`users`.`remember_token` IS NULL)" 
ruby-1.9.2-p180 :030 > User.where("remember_token = ?", nil).to_sql
 => "SELECT `users`.* FROM `users` WHERE (remember_token = NULL)

Upvotes: 5

Related Questions