2013-02-25 57 views
0

我是Ruby on Rails的新手。我有2個型號:DevicePropertyDevice包含以下字段:id,nameProperty包含:文件id,device_id,speed,timedevice_id是模型Device中表id的外鍵。所以,我的模型device.rb和property.rb是如下所示:從兩個表中提取值

device.rb

class Device < ActiveRecord::Base 
    attr_accessible :name 
    has_many :properties 
end 

property.rb

class Property < ActiveRecord::Base 
    attr_accessible :device_id, :speed, :time 
    belongs_to :device 
end 

我有一個下拉列表填充設備的詳細信息。它工作正常。 我還必須從屬性數據庫中提取值,同時從下拉列表中選擇名稱。在屬性表

def show 
    @properties = Property.find(params[:device][:id]) 
end 

測試值如下::

id device_id time   speed 
1 1   13:23:00  13 
2 2   23:20:00  63.8  
3 1   10:35:  100.56 

設備型號:

id name  
1 2345  
2 2345 

控制器代碼,以通過將設備ID如下取的值在選擇設備型號ID 1時,我必須獲取以下詳細信息:

id device_id  time   speed  
1 1    13:23:00   13 
3 1    10:35:00   100.56 

鑑於show.html.erb如下:

<% if (@properties.blank?) %> 
    <p><strong>Search results not found.</strong></p> 
<% else %> 
    <p><strong>Available employe Details are listed below <strong></p> 
    <ul> 
    <% @properties.each do |c| %> 
    <li> 
     <b><%[email protected]%> <%[email protected]%> <%[email protected]%></b> 
    </li> 
    <% end %> 
</ul> 
<% end %> 

在運行這個正在此錯誤

undefined method `each' for #<Property:0x3ee3ff8> 
10: <% else %> 
11: <p><strong>Available employe Details are listed below <strong></p> 
12: <ul> 
13: <% @properties.each do |c| %> 
14: <li> 
15: <b><%[email protected]%> <%[email protected]%> <%[email protected]%></b> 
16: </li> 

但同時擰show.html.erb如下面的方式只有一個數據越來越

id device_id  time   speed  
1 1    13:23:00   13 



<% if (@properties.blank?) %> 
    <p><strong>Search results not found.</strong></p> 
<% else %> 
    <p><strong>Available employe Details are listed below <strong></p> 
    <ul><li> 
    <b><%[email protected]%> <%[email protected]%> <%[email protected]%></b> 
    </li></ul> 
<% end %> 
+0

一方面'遍歷Property.find'將只返回一個對象。它不會是一個集合,所以你不能在它上面調用'each'。 – Mischa 2013-02-25 11:46:04

回答

4
@properties = Property.find(params[:device][:id]) 

只會返回一個屬性,而不是一個數組

您需要所以像

@properties = Property.where(:device_id => params[:device][:id]) 

爲了得到一個數組,然後你可以用每個

+1

或者:@properties = Device.find(params [:device] [:id])。properties' – Mischa 2013-02-25 11:48:28

+0

@Mischa true,雖然這會創建更多的數據庫調用並不必要地檢索設備信息。 – Damp 2013-02-25 13:36:05

+0

是的,你說得對。沒有想到這一點。 – Mischa 2013-02-25 13:42:05