0

我有以下数据库:

class User < ActiveRecord::Base
  has_and_belongs_to_many :apps

class App < ActiveRecord::Base
  has_and_belongs_to_many :users

在 User ( users/show.html.haml) 视图中,我想列出所有按当前用户拥有的应用程序排序的应用程序。

%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

我的问题是我在 order 函数中放入什么来进行排序。

4

4 回答 4

2

或通过类似这样的方式:

App.all.partition{|app| @user.apps.include?(app)}.flatten

有不止一种方法可以做到!

于 2012-04-10T12:53:09.543 回答
1

如果我理解正确,您希望将属于当前用户的应用程序排在第一位。我认为这在一个查询中是不可能的。我认为最简单的方法是将其拆分为两个查询:

user_apps     = current_user.apps
non_user_apps = App.where(:id.not_in => current_user.app_ids)
@apps         = user_apps + non_user_apps

然后你可以迭代这个@apps数组,元素将按照你想要的顺序排列。

于 2012-04-10T12:30:27.083 回答
0

试试这个:@user.apps.order(:name)

于 2012-04-10T13:20:29.673 回答
0

在 order 方法中,您可以输入您想要的任何 App 的方法名称。有可能

App.order(:id)
App.order(:name)
App.order(:created_at)

或其他任何东西。

于 2012-04-10T11:59:10.613 回答