Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9365

How to get data in has_many :through association?

I'm following this tutorial and this tutorial to learn more about has_many :through association in Rails. I created an app called school. And I have this inside my schema.rb file:

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

My teacher model:

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

My student model:

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

My course model:

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

And my /courses view now looks something like this (I'm using scaffold):

enter image description here

When I go to /teachers/1, I want to display all students name and quantity associated with that teacher.

The current view of /teachers/1 is like this:

enter image description here

I try to make it by using this code but it's not working:

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

So, how to display all students name and quantity associated with that teacher?

Upvotes: 0

Views: 2189

Answers (3)

msergeant
msergeant

Reputation: 4801

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

Upvotes: 2

Zulhilmi Zainudin
Zulhilmi Zainudin

Reputation: 9365

Solved with this code:

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

Thanks to msergeant and Jan!

Upvotes: 0

Jan Strn&#225;dek
Jan Strn&#225;dek

Reputation: 808

You have to use the name of relation on variable with teacher object.

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

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

Upvotes: 1

Related Questions