hellion
hellion

Reputation: 4830

Rails Order Find By Boolean

I have a simple find in rails 3 that gathers users accounts.

 Account.where(:user_id => @user)

The Account model has a 'default' boolean field. As a user adds many accounts I would like the default account to always be first in the loop. Order doesn't seem to work with a boolean field.

  Account.where(:user_id => @user, :order => "default DESC")

Is there a way to order the query to handle this or should I just split the queries and find the default account in a separate find?

Upvotes: 0

Views: 2316

Answers (1)

Chris Heald
Chris Heald

Reputation: 62648

Try Account.where(:user_id => @user).order("default DESC") - putting :order in your where() clause isn't going to sort the result set.

A cleaner solution might be to add a scope, though.

scope :default_first, order(arel_table[:default].desc) 

Then you could just call (assuming your relations are set up properly):

@user.accounts.default_first.all

Upvotes: 4

Related Questions