我有一個用戶索引,其中顯示用戶名,用戶位置和一個名爲categories的字段,其範圍可以從零到多個項目。我無法正確顯示類別。這裏是我的個人資料:Rails - 從連接表中調用列的問題
用戶
has_many :user_categories
has_many :categories, :through => :user_categories
分類
has_many :user_categories
has_many :users, :through => :user_categories
User_categories
belongs_to :user
belongs_to :category
在我的user_categories表中,有三列:id,user_id,category_id。
在我的分類表中,有兩列:id和name。
在我的用戶/索引視圖,我有以下幾點:
<% @users.each do |user| %>
<%= link_to user.name, user %>
<%=h user.state %>
<%=h user.categories %> ## This line is the problem
<% end %>
在那裏我已經指出,直接上面我的意見的問題,我已經嘗試了多種變化,但不知何故,我很想念它。以下是我嘗試過的變體以及它們產生的結果。請注意,對於測試,用戶#2是唯一一個應該顯示的類別。
<%=h user.categories %>
顯示:#<Category:0x3f40634>
日誌顯示:
UserCategory Load (0.4ms) SELECT * FROM "user_categories" WHERE ("user_categories".user_id = 2)
Category Load (0.4ms) SELECT "categories".* FROM "categories" INNER JOIN "user_categories" ON "categories".id = "user_categories".category_id WHERE (("user_categories".user_id = 2))
<%=h user.categories.name %> <-- Here I added .name at the end of the call
顯示:category
日誌顯示:應用程序不會做一個類別負荷。
<%=h user.user_categories %>
顯示:#<UserCategory:0x3e4d1a0>
日誌顯示:UserCategory Load (0.4ms) SELECT * FROM "user_categories" WHERE ("user_categories"."user_id" = 2) AND ("user_categories".user_id = 2) LIMIT 1
沒有做一個類別負荷。
<%=h user.user_categories.find_by_user_id(user.id) %>
產生與上述相同的結果。
基於此,我認爲<%= h user.categories%>是最有意義的,但我嘗試了每個我能想到的變體,它們都會拋出異常。
工作。任何想法爲什麼我以前的方法不起作用?我不確定我是否明白問題所在。 – MikeH 2009-09-23 02:55:18
這個答案是正確的錢。僅僅是持有@用戶類別的Array對象的字符串表示形式。 –
hgmnz
2009-09-23 02:57:18
查看我的答案進一步解釋 - 它不適合評論。 – 2009-09-23 03:13:30