0

I would like to display a list of phases from a project. For that I load all phases in the controller

def load_project
    @project = Project.find params[:id]
    @phases = @project.phases
end

Then I go through @phases using the each function in the haml

- @phases.each do |phase|
    %tr ...

The problem is that the sql request from previous code doesn't have any order attribute, so it's the default order by id.

SELECT `phases`.* FROM `phases` WHERE `phases`.`project_id` = 123

I would like to order this request by a phases attribute call "position". Is it possible to add an order option ?

Luckyn
  • 563
  • 1
  • 4
  • 21

3 Answers3

1

You can add order in controller, or in view

def load_project
    @project = Project.find params[:id]
    @phases = @project.phases.order(:position)
end

Or

- @phases.order(:position).each do |phase|
    %tr ...
Nermin
  • 6,118
  • 13
  • 23
  • Thanks for the syntax, but I'll use @test model's edit so I don't need to think about adding order everytime :) – Luckyn Jul 20 '15 at 10:19
1

try this

@phases = @project.phases.order("position ASC")

rather add scope to the model phases like this

scope :ordered, order: "position ASC"

and call this way

@phases = @project.phases.ordered
Athar
  • 3,258
  • 1
  • 11
  • 16
1

project.rb

has_many :phrases, order: 'phrases.column_name'

So this will order all phrases of your project with column_name you specified

You can do this if you want by default association should be ordered

Vrushali Pawar
  • 3,753
  • 1
  • 13
  • 22
  • I didn't knew you can add order to the model, thanx :) Just a note, order looks to be deprecated in rails 4, should use scope block instead : http://stackoverflow.com/a/18284635/3703099 – Luckyn Jul 20 '15 at 10:15