scott
scott

Reputation: 441

Obtaining ActiveRecords if NOT nil

I would like to be able to gather all records in a table where the user_id is not null. This is what I have but it doesn't seem to be working (even though I've had it working in a seperate project):

named_scope :all_registered, :conditions => ["user_id != ?", nil]

Upvotes: 3

Views: 888

Answers (3)

user2713480
user2713480

Reputation:

In Rails 4 you can use NOT conditions, see Active Record Query Interface

e.g:

User.where.not(id: nil)

or as a scope:

scope :all_registered, -> { where.not(user_id: nil) }

Upvotes: 0

Tomas Markauskas
Tomas Markauskas

Reputation: 11596

This should work:

named_scope :all_registered, :conditions => "user_id IS NOT NULL"

Upvotes: 1

Vincent Robert
Vincent Robert

Reputation: 36150

SQL has a specific operator to check for NULL: IS NULL and IS NOT NULL

named_scope :all_registered, :conditions => ["user_id IS NOT NULL"]

Upvotes: 8

Related Questions