2010-04-22 82 views
4

我有兩個以多對多關係建立的表格:事件和用戶。當用戶登錄後,他們查看/事件頁面(索引),我想要顯示與它們關聯的所有事件。不幸的是,出現以下錯誤:Rails:在多對多關係中找不到表格

Could not find table 'incidents_users' 

看來Rails是尋找表「incidents_users」,當我真正創建表「users_incidents」。 'users_incidents'只保存user_id和incident_id。

我失去了一些東西明顯?我對rails比較陌生,所以問題可能很簡單,我忽略了。

這裏是incidents_controller.rb

# GET /incidents 
# GET /incidents.xml 
def index 
    @incidents = current_user.incidents 

    respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @incidents } 
    end 
end 

這裏的相關部分是index.html.erb

<% for incident in @incidents %> 
    <tr> 
    <td><%=h incident.other_id %></td> 
    <td><%=h incident.title %></td> 
    <td><%= link_to 'Show', [@customer, incident] %></td> 
    <td><%= link_to 'Edit', edit_customer_incident_path(@customer, incident) %></td> 
    <td><%= link_to 'Destroy', [@customer, incident], :confirm => 'Are you sure?', :method => :delete %></td> 
    </tr> 
<% end %> 

感謝有關節!請讓我知道,如果更多的信息會有所幫助。

回答

10

您的連接表必須被稱爲incidents_users,因爲Rails使用has_and_belongs_to_many關聯時的慣例是表名是從構成關聯的模型的類名稱的詞法順序派生而來的。

documentation

因此開發人員和項目 會以默認之間的連接加入「developers_projects」的 表名 因爲「d」級別高於「P」。請注意, 此優先級是使用 對於String的<運算符計算的。這意味着該 如果字符串不同 長度,並且當相比較高達最短 長度,則較長的字符串是 考慮更高詞法 優先比中較短的字符串相等 。對於 例如,人們可能會期望表 「paper_boxes」和「論文」,以產生 聯接的 「papers_paper_boxes」表名稱,因爲 長的名字「paper_boxes」,但 它實際上是產生一個連接表「paper_boxes_papers」的名稱 。

注意到,該表名可以指定關聯時,所以使用:join_table選項覆蓋:

class Incident < ActiveRecord::Base 
    has_and_belongs_to_many :users, :join_table => 'users_incidents' 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :incidents, :join_table => 'users_incidents' 
end 

—通常最好只是去與Rails的約定,雖然,除非您已這是阻止你的特殊原因。

+0

那很簡單吧?謝謝! :) – Magicked 2010-04-22 13:11:59

+0

哇,謝謝你的更新!我正在慢慢學習如何理解官方API文檔。我非常感謝你的幫助。 – Magicked 2010-04-22 13:23:52

+0

沒問題:-)不要忘記Rails指南:http://guides.rubyonrails.org/ – 2010-04-22 13:27:33