加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails:’无法在多对多关系中找到表’

发布时间:2020-12-17 03:51:25 所属栏目:百科 来源:网络整理
导读:我有两个以多对多关系设置的表:事件和用户.当用户登录并查看/事件页面(索引)时,我想显示与之关联的所有事件.不幸的是,发生以下错误: Could not find table 'incidents_users' 当我实际创建表’users_incidents’时,看起来rails正在寻找表’incidents_users
我有两个以多对多关系设置的表:事件和用户.当用户登录并查看/事件页面(索引)时,我想显示与之关联的所有事件.不幸的是,发生以下错误:

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:

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的惯例,除非你有一个特殊的原因阻止你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读