Rails: "Could not find table" in many-to-many relationships

I have two tables created in a many-to-many relationship: Incidents and Users. When the user is logged in and browsing the page / incidents (index), I want to show all the incidents with which they are associated. Unfortunately, the following error occurs:

Could not find table 'incidents_users' 

It seems the rails are looking for the tables "incidents_users" when I actually created the table "users_incidents". "users_incidents" just contains user_id and event_id.

Am I missing something obvious? I am relatively new to rails, so the problem may be something simple that I missed.

Here is the relevant section 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 

Here is the relevant index.html.erb section

 <% 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 %> 

Thanks! Please let me know if further information is helpful.

+4
source share
1 answer

Your join table should be called by incidents_users , because the Rails convention when using the has_and_belongs_to_many association is that the table name comes from the lexical order of the names of model classes that contain the association.

In the documentation:

So, the connection between the developer and the Project will provide a default connection to the table name "developers_projects" because "D" is superior to "P". Note that this priority is calculated using the <operator for String. This means that if the lines have different lengths, and the lines are equal when comparing to the shortest length, then a longer line is considered more lexical than shorter. For example, one would expect the paper_boxes and documents tables to generate a paper_boxes paper table name because of the paper_boxes name length, but it actually generates a paper table name from paper_boxes_papers.

Note that the table name can be overridden with the :join_table parameter when specifying an association, therefore:

 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 

- As a rule, it is best to go with Rails conventions, although if you have a specific reason that is bothering you.

+9
source

Source: https://habr.com/ru/post/1307671/


All Articles