1

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!

1
  • 3
    Booking.scoped should work for you. Commented Apr 18, 2013 at 14:13

2 Answers 2

1

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?

Sign up to request clarification or add additional context in comments.

Comments

0

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.