0

私は次のデータベースを持っています:

class User < ActiveRecord::Base
  has_and_belongs_to_many :apps

class App < ActiveRecord::Base
  has_and_belongs_to_many :users

ユーザーのビュー( )で、現在のユーザーが持っているアプリでソートされたすべて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

私が正しく理解している場合は、現在のユーザーに属するアプリを最初に並べ替えます。これは1つのクエリでは不可能だと思います。最も簡単な方法は、2つのクエリに分割することだと思います。

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

orderメソッドには、任意のアプリのメソッド名を入力できます。かもね

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

または他の何か。

于 2012-04-10T11:59:10.613 に答える
0

これを試してください:@ user.apps.order(:name)

于 2012-04-10T13:20:29.673 に答える