如何获取 has_many 中的数据:通过关联?

How to get data in has_many :through association?

我正在关注 this tutorial and this tutorial 以了解有关 has_many 的更多信息:通过 Rails 中的关联。我创建了一个名为 school 的应用程序。我的 schema.rb 文件中有这个:

create_table "courses", force: :cascade do |t|
    t.integer  "teacher_id"
    t.integer  "student_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "quantity"
  end

  create_table "students", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "teachers", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

我的老师模型:

class Teacher < ActiveRecord::Base
    has_many :courses
    has_many :students, :through => :courses
end

我的学生模型:

class Student < ActiveRecord::Base
    has_many :courses
    has_many :teachers, :through => :courses
end

我的课程模型:

class Course < ActiveRecord::Base
    belongs_to :teacher
    belongs_to :student
end

我的 /courses 视图现在看起来像这样(我正在使用脚手架):

当我转到 /teachers/1 时,我想显示与该老师相关的所有 students 姓名和 quantity

目前/teachers/1的看法是这样的:

我尝试使用此代码实现它,但它不起作用:

<% @course.each do |c| %>
    <p><%= c.quantity %></p>
<% end %>

那么,如何显示与该老师关联的所有 students 姓名和 quantity

您必须使用与教师对象的变量关系名称。

<% @teacher.courses.each do |c| %>
  <%= c.quantity %>
<% end %>

<% @teacher.students.each do |s| %>
  <%= s.name %>
<% end %>
<% @teacher.courses.each do |c| %>
    <p><%= c.student.name %></p>
    <p><%= c.quantity %></p>
<% end %>

使用此代码解决:

<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @teacher.name %>
</p>

<table>
<tr>
<th>Student Name</th>
<th>Quantity</th>
</tr>
<% @teacher.courses.each do |c| %>
    <tr>
        <td><%= c.student.name %></td>
        <td><%= c.quantity %></td>
    </tr>
<% end %>
</table>

<%= link_to 'Edit', edit_teacher_path(@teacher) %> |
<%= link_to 'Back', teachers_path %>

感谢 mssergeant 和 Jan!