Reputation: 63
Getting "undefined method `each' for #< Mark:0x00000001e057d0>"
Here is the view:
<% @current_marks.each do |m| %>
<tr>
<td class='col-md-3'><%= m.subject %></td>
<td class='col-md-3'><%= m.professor %></td>
<td class='col-md-3'><%= m.semester %></td>
<td class='col-md-3'><%= m.points %></td>
</tr>
<% end %>
And a controller:
def show
@student = Student.find(params[:id])
@students = Student.all
@current_marks = Mark.find_by! student_id: @student.id
rescue ActiveRecord::RecordNotFound
redirect_to :action => 'set_marks'
end
I've checked an Id param already and it is correct. Also I have Mark
records in DB with correct student_id
. How should I call @current_marks
without any errors?
Upvotes: 2
Views: 91
Reputation: 76774
To add to punitcse
's answer, you'll also want to check your associations because invoking two class calls like you have is pretty inefficient.
--
You should be able to get away with:
def show
@student = Student.find params[:id]
@current_marks = @student.marks
end
This is considering the following to be set up in your models:
#app/models/student.rb
class Student < ActiveRecord::Base
has_many :marks
end
#app/models/mark.rb
class Mark < ActiveRecord::Base
belongs_to :student
end
Upvotes: 2
Reputation: 727
find_by
will give you the first matched record not a collection so you can not call each on that.Instead you can use where if you need all matched record
@current_marks = Mark.where student_id: @student.id
Upvotes: 7