Reputation: 4375
I have the following database:
class User < ActiveRecord::Base
has_and_belongs_to_many :apps
class App < ActiveRecord::Base
has_and_belongs_to_many :users
In the view for a User (users/show.html.haml
) I want to list all the Apps sorted by the ones the current user has.
%table
%thead
%tr
%th Name
%th Available
- for app in App.order("??????")
%tr
%td= link_to app.name, app_path(app)
%td
- if @user.apps.include?(app)
%i.icon-ok
- else
%i.icon-remove
My question is what do I put in the order function to do the sort.
Upvotes: 0
Views: 339
Reputation: 15779
or via something like this:
App.all.partition{|app| @user.apps.include?(app)}.flatten
There is more than one way to do it!
Upvotes: 2
Reputation: 11710
If I understand right, you want to sort the apps with the ones belonging to the current user coming first. I don't think this is possible in one query. I think the simplest way would be to split it into two queries:
user_apps = current_user.apps
non_user_apps = App.where(:id.not_in => current_user.app_ids)
@apps = user_apps + non_user_apps
Then you can just iterate over this @apps
array, and the elements will be in the order you want.
Upvotes: 1
Reputation: 9851
In the order method you can put any App's method name you want. It can be
App.order(:id)
App.order(:name)
App.order(:created_at)
or anything else.
Upvotes: 0