2011-06-09 51 views
0

選擇數據我有以下結構:從兩個表,並列出

class User < ActiveRecord::Base 
    has_many :Hobbies, :dependent => :destroy 
    accepts_nested_attributes_for :hobbies, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 
end 

class Hobby < ActiveRecord::Base 
    belongs_to :User 
end 

在我Users_controller.rb

def index 
    @data = User.all(:joins => :hobbies) 
    end 

index.html.erb

<% for item in @data %> 
    <tr> 
     <td><%= item.id %></td> #from table Users 
     <td><%= item.hobby_name %></td> #from table Hobbies 
    </tr> 
    <% end %> 

這給我一個錯誤未定義的方法`hobby_name'爲#用戶:0x103cf7480>

我以爲我有那種關聯是正確的,

回答

1

必須指定的關係,你的對象沒有叫hobby_name一個屬性,它有一個關聯到多個興趣愛好,每個愛好有

所謂hobby_name屬性:

<% item.hobbies.each do |h| %> 
<%= h.hobby_name %> 
<% end %> 
+0

謝謝你,Kelend! – user1946705 2011-06-09 21:42:27