tomraithel
tomraithel

Reputation: 968

Rails 3: Create an "empty" ActiveRecord query object

Is it possible in Rails, to create an "empty" ActiveRecord Query object for a given model? Empty means for me a condition, that includes all possible rows in the db. I want to apply filters to that query afterwards.

At the moment I am using Booking.where('id > ?', 0), but I believe there has to be a nicer way like Booking.all() - but all() returns an array and not an ActiveRecord. Here´s my code:

@bookings = Booking.where('id > ?', 0)
if [email protected]?
    @bookings = @bookings.where('day = ?',@day)
end
if @project_id && !@project_id.empty?
    @bookings = @bookings.where('project_id = ?', @project_id)
end

Thanks for your help!

Upvotes: 1

Views: 1108

Answers (2)

mahemoff
mahemoff

Reputation: 46409

Use unscoped to create an empty query so you can build on it. (scoped is deprecated).

@bookings = Booking.unscoped
if [email protected]?
    @bookings = @bookings.where('day = ?',@day)
end
if @project_id && !@project_id.empty?
    @bookings = @bookings.where('project_id = ?', @project_id)
end

(BTW in the absence of this you could also initialise it with Booking.where(true) instead of the id > 0 check; it's cleaner and likely to perform be better than doing a real condition check. But, unscoped is better still.)

Upvotes: 0

Shawn Balestracci
Shawn Balestracci

Reputation: 7530

You can use the scoped method discussed here: http://guides.rubyonrails.org/active_record_querying.html#working-with-scopes

Also note that @project_id.present? is the same as @project_id && !@project_id.empty?

Upvotes: 1

Related Questions