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

时间:2015-07-14 20:06:41

标签: ruby-on-rails ruby ruby-on-rails-4 associations has-many-through

我正在关注this tutorialthis 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视图现在看起来像这样(我正在使用脚手架):

enter image description here

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

/teachers/1的当前视图是这样的:

enter image description here

我试图通过使用此代码来实现它,但它不起作用:

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

那么,如何显示与该教师相关联的所有students名称和quantity

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

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

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

<% @teacher.students.each do |s| %>
  <%= s.name %>
<% end %>

答案 2 :(得分:0)

解决了这段代码:

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

感谢msergeant和Jan!