Reputation: 43
I am dealing with main users (teachers) and their students. They share the user's id
and the student's teacher_id
. I want to list all the students that have the same teacher_id
as the current user's id
, so the user can see all their students. This is my code:
<% @students = Student.all %>
<% if @students[:teacher_id] == @current_user.id %>
<% @students.each do |students| %>
Username: <%= students.username %><br/>
Name: <%= students.name %><br/>
<% end %>
<% end %>
And I am getting the following error:
no implicit conversion of Symbol into Integer
What is going on? The logic seems sound: if the teacher_id
is the same as the current_user
id, print the students.
Upvotes: 1
Views: 55
Reputation: 23317
You are calling [:teacher_id]
on @students
, which is an ActiveRecord
relationship. You can think about it as an array. You should rather call it on an individual student by moving the if
inside the iteration:
<% @students = Student.all %>
<% @students.each do |student| %>
<% if student[:teacher_id] == @current_user.id %>
Username: <%= student.username %><br/>
Name: <%= student.name %><br/>
<% end %>
<% end %>
There are some improvements you can do:
Student.all
) in view, move it to the controller.Student.where(teacher_id: @current_user.id)
instead of Student.all
and checking hash value.Finally you'll get
# controller:
@students = Student.where(teacher_id: @current_user.id)
# view:
<% @students.each do |student| %>
Username: <%= student.username %><br/>
Name: <%= student.name %><br/>
<% end %>
Upvotes: 1