The following error message occurred while implementing the function to acquire all the information of the table and acquire the value of another table via the intermediate table associated with the acquired value.

Corresponding source code

Where the error occurred

<% @ task.each do | g |%>
 <p><% = g.genre_task.genre.user_id%></p>
<% end%>

Controller of the corresponding part

def index
  @task = Task.order (id :: DESC) .all

Genre model

class Genre</pre>
<p><br />
Task model</p>
<pre><code data-language = "model">class Task</pre>
<p><br />
Intermediate table model</p>
<pre><code data-language = "model">class GenreTask</pre>
<p><br />
genres table</p>
<pre><code data-language = "Ruby">class CreateGenres</pre>
<p><br />
tasks table</p>
<pre><code data-language = "Ruby">class CreateTasks</pre>
<p><br />
Intermediate table</p>
<pre><code data-language = "Ruby">class CreateGenreTasks</pre>
<strong>What I tried</strong>
<p>Since NoMethodError is displayed, I thought that the specified method was different and searched on the net. However, changing the method specification did not resolve the error. Therefore, I thought that there might be another cause, so I acquired the value of the intermediate table on the console and checked whether the association was established.</p>
<pre><code>[1] pry (main)>@genre_task = GenreTask.find (1)
  GenreTask Load (0.4ms) SELECT `genre_tasks`. * FROM` genre_tasks` WHERE `genre_tasks`.`id` = 1 LIMIT 1
=>#<GenreTask: 0x00007fd038cadae0 id: 1, genre_id: 1, task_id: 1, created_at: Wed, 18 Nov 2020 09:29:14 UTC +00: 00, updated_at: Wed, 18 Nov 2020 09:29:14 UTC +00: 00>
[2] pry (main)>@ genre_task.genre
  Genre Load (0.3ms) SELECT `genres`. * FROM` genres` WHERE `genres`.`id` = 1 LIMIT 1
=>#<Genre: 0x00007fd03ea07bf0 id: 1, text: "test", name: "test", user_id: 1, created_at: Wed, 18 Nov 2020 09:29:04 UTC +00: 00, updated_at: Wed, 18 Nov 2020 09:29:04 UTC +00: 00>

Therefore, it turned out that it is not impossible to obtain the value of the association.
So I think the way to call the values ​​in the intermediate table is wrong, but I don't know what to do.

Supplementary information (FW/tool version, etc.)

Ruby on Rails ver6.0.0
Ruby ver2.6

  • Answer # 1

    To Takshas_many: genres, through :: genre_tasksSo I have a method called genre_tasks, but there is no singular.
    If you want to get the user of the genre of the task multiple, you have to take the multiple.

    <% g.genres.each do | genre |%>
    <p><% = genre.user_id%></p>

    is not it.
    In addition, in Taskhas_many: genre_tasksIs required.