1

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.

4

2 回答 2

1

作为 device_ports 属于_to 设备,所以list_item.device.name谢谢!

于 2013-08-06T13:09:44.617 回答
1

我刚刚在控制台中对此进行了测试,但它应该可以工作。您可以调用columns返回数组的模型。

所以,我刚刚使用了我的用户模型:

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

大概你的将是

Device.columns[x].name

编辑:我把这个问题读作“列名”

于 2013-08-06T13:13:09.553 回答