我有两个以多对多关系设置的表:事件和用户.当用户登录并查看/事件页面(索引)时,我想显示与之关联的所有事件.不幸的是,发生以下错误:
Could not find table 'incidents_users'
Run Code Online (Sandbox Code Playgroud)
当我实际创建表'users_incidents'时,看起来rails正在寻找表'incidents_users'.'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
Run Code Online (Sandbox Code Playgroud)
这是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 %>
Run Code Online (Sandbox Code Playgroud)
谢谢!如果有更多信息有用,请告诉我.
Joh*_*ley 10
必须调用连接表,incidents_users因为使用has_and_belongs_to_many关联时Rails的约定是表名是从组成关联的模型的类名的词法顺序派生的.
从文档:
因此,Developer和Project之间的连接将提供默认的连接表名称"developers_projects",因为"D"超出"P".请注意,此优先级使用<operator for String计算.这意味着如果字符串具有不同的长度,并且在比较最短长度时字符串相等,则较长字符串被认为具有比较短字符串更高的词汇优先级.例如,由于名称"paper_boxes"的长度,人们会期望表"paper_boxes"和"papers"生成连接表名称"papers_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
Run Code Online (Sandbox Code Playgroud)
- 通常最好只是遵循Rails的惯例,除非你有一个特殊的原因阻止你.
| 归档时间: |
|
| 查看次数: |
1240 次 |
| 最近记录: |