gpt4 book ai didi

ruby-on-rails - rails : 'Could not find table' in a many-to-many relationship

转载 作者:行者123 更新时间:2023-12-03 16:20:21 25 4
gpt4 key购买 nike

我在多对多关系中设置了两个表:事件和用户。当用户登录并查看/incidents 页面(索引)时,我想显示与他们关联的所有事件。不幸的是,出现以下错误:

Could not find table 'incidents_users'

当我实际创建表 'users_incidents' 时,rails 似乎正在寻找表 'incidents_users'。 'users_incidents' 只包含 user_id 和 event_id。

我错过了一些明显的东西吗?我对 Rails 比较陌生,所以问题可能很简单,但我忽略了。

这是 events_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 %>

谢谢!如果更多信息有帮助,请告诉我。

最佳答案

您的连接表必须被称为 incidents_users因为 Rails 在使用 has_and_belongs_to_many 时的约定关联是表名派生自构成关联的模型的类名的词汇顺序。

来自 documentation :

So a join between Developer and Project will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence is calculated using the < operator for String. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "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 的约定,除非您有特殊原因阻止您。

关于ruby-on-rails - rails : 'Could not find table' in a many-to-many relationship,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2690983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com