martincarlin87
martincarlin87

Reputation: 11042

How to get name of foreign key

In my Rails app I have a list view of device ports and each device port belongs to a device:

device.rb

has_many :device_ports, :foreign_key => "device_id"

device_port.rb

belongs_to :device

device_port_controller.rb

def list
    @device_ports = DevicePort.paginate(:all, :page => params[:page], :per_page => 100, :order => "name")
    @devices = Device.find(:all)
end

list.rhtml

<table width="100%">
    <tr>
        <th>Name</th>
        <th>Device</th>
    </tr>

    <%= render :partial => 'device_port/list_item', :collection => @device_ports %>
</table>

_list_item.rhtml

<tr>
    <td><a href='/device_port/update/<%= list_item.id %>'><%= list_item.name %></a></td>
    <td><%= list_item.device_id %></td>
</tr>

So I am displaying the device_id from the device_ports table but I actually want to display the name column of the devices table instead.

I have done something very similar and probably slightly more difficult elsewhere in my app where I have a preselected dropdown with the correct device name selected but I can't seem to figure out how to do it outwith the context of a select menu.

I have the devices in the @devices variable in the controller above and was trying to look that up using the list_item.device_id but it didn't seem to work.

It's probably quite a straightforward thing but I just can't seem to find the proper way of getting the desired result.

Upvotes: 1

Views: 470

Answers (2)

MCB
MCB

Reputation: 2073

I just tested this out in the console but it should work. You can call columns on your model which returns an array.

So, what I just used my User model:

User.columns[0].name #=> 'id'

Presumably yours will be

Device.columns[x].name

EDIT: I read the the question as "name [of the] column"

Upvotes: 1

Rajarshi Das
Rajarshi Das

Reputation: 12320

as device_ports belongs_to device so list_item.device.name Thanks!

Upvotes: 1

Related Questions