3

Each company in my database has many projects, and every company is given a 'General tasks' project when they sign up. This particular project cannot be deleted by its company, and it is treated as a special repository for tasks that have not yet been assigned to one of the company's other projects.

When displaying the company's projects, I want them to appear in alphabetical order but with the single exception that 'General tasks' appears at the top. This requires some kind of special handling of the project for sorting purposes. How can I take:

@projects = @company.projects

and sort it so we get a list like this:

'General tasks'
'ABC Project'
'BFA Project'
'ZNS Project'
4

2 に答える 2

2

これは SQL で行うことができます。これは PostgreSQL で動作する例です。データベースに依存しないバージョンを作成する方法がわかりませんでしたが、RDBMS に合わせて調整できるはずです。

@projects = @company.projects.order("name != 'General tasks', name")

!=はブール値を返します。PostgreSQL ではfalseが前に来るtrueため、"General tasks" という名前のレコードが最初に表示されるようにするために NOT EQUAL は必要ありません。残りのプロジェクトは名前順にソートされます。

別のアプローチは、次のように、「一般的なタスク」プロジェクトに特別なフラグを立てる列をプロジェクト テーブルに追加することです。

add_column :projects, :permanent, :boolean, :default => false

次に、生の SQL を使用せずに並べ替えることができます。

@projects = @company.projects.order(:permanent, :name)
于 2012-05-30T21:38:00.410 に答える