martincarlin87
martincarlin87

Reputation: 11042

Use :order with find_by_id

In my Rails application I have a Device and a DevicePort class with a one to many relationship between them.

In my device controller I get a list of all the ports belonging to that device but I can't seem to order them:

@device_ports = Device.find_by_id(params[:id], :order => 'id ASC').device_ports

This doesn't seem to work and doesn't give any syntax errors either.

In the view I am simply doing:

<% @device_ports.each do |device_port| %>
    ...
<% end %>

Is anyone able to explain why the ports aren't being sorted by id?

Upvotes: 1

Views: 76

Answers (3)

Marek Lipka
Marek Lipka

Reputation: 51151

If you want to order device_ports, I'd do something like this:

@device_ports = Device.find(params[:id]).device_ports.all(:order => 'id ASC')

Upvotes: 2

Salil
Salil

Reputation: 47472

@device_ports = Device.exists?(params[:id]) ? Device.find_by_id(params[:id]).device_ports : []

if you want order on device sports do following

@device_ports = Device.exists?(params[:id]) ? Device.find_by_id(params[:id]).device_ports.order('id ASC') : []

For rails 2.x.x use following

@device_ports = DeviceSport.find(:all, :conditions => ["device_id = ?", params[:id]], :order => 'id ASC' )

Upvotes: 1

MurifoX
MurifoX

Reputation: 15089

Well, you are ordering just the devices, the ports are randomly being fetched. You can eager load your association and order the ports with this:

Device.includes(:device_ports).where('devices.id = ?', params[:id]).order('device_ports.id')

Make note about the query that is generated. You have access to the ports table when you join them.

UPDATE:

If you want the other way around:

DevicePort.includes(:device).where('devices.id = ?', params[:id]).order('device_ports.id')

Only the association inside the includes is changed.

Upvotes: 1

Related Questions