2013-08-06 81 views
1

的名字在我的Rails應用程序我有設備端口的列表視圖和每個設備端口所屬的設備:如何獲得的外鍵

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> 

所以我從device_ports表顯示device_id但其實我是想顯示name表1中的devices列nstead。

我做了一些非常相似的事情,可能在我的應用程序的其他地方稍微有些困難,我有一個預選的下拉列表,並選擇了正確的設備名稱,但我似乎無法弄清楚如何使用select菜單。

我在上面的控制器中的@devices變量的設備,並試圖用list_item.device_id來查看,但它似乎沒有工作。

這可能是相當直接的事情,但我似乎無法找到獲得理想結果的正確方法。

+0

as device_ports belongs_to device so'list_item.device.name'謝謝! –

回答

1

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

+0

該死的,我知道這會很容易,但我只是沒有關於語法的線索,謝謝你救了我的理智! – martincarlin87

1

我剛剛在控制檯中測試了這一點,但它應該可以工作。您可以在返回數組的模型上調用columns

所以,我只是用我的用戶模型:

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

想必你的將是

Device.columns[x].name 

編輯:我讀了一個問題,

「列[中的]名」
+0

感謝MCB,但Rajarshi的回答正是我所需要的。 – martincarlin87