ruby-on-rails – Rails:’无法在多对多关系中找到表’
我有两个以多对多关系设置的表:事件和用户.当用户登录并查看/事件页面(索引)时,我想显示与之关联的所有事件.不幸的是,发生以下错误:
Could not find table 'incidents_users' 当我实际创建表’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 这是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',incident],:confirm => 'Are you sure?',:method => :delete %></td> </tr> <% end %> 谢谢!如果有更多信息有用,请告诉我. 解决方法
您的连接表必须被称为incidents_users,因为使用has_and_belongs_to_many关联时Rails的约定是表名是从组成关联的模型的类名的词汇顺序派生的.
从documentation:
请注意,在指定关联时,可以使用: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的惯例,除非你有一个特殊的原因阻止你. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |