James Brooks
James Brooks

Reputation: 4375

Sorting habtm data in rails

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

Answers (4)

Ben Miller
Ben Miller

Reputation: 1484

Try this: @user.apps.order(:name)

Upvotes: 0

jdoe
jdoe

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

tsherif
tsherif

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

denis.peplin
denis.peplin

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

Related Questions