简体   繁体   中英

Getting strange 'undefined method ' error

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?

find_by将为您提供第一个匹配的记录而不是一个集合,因此您不能在每个上面调用。相反,如果您需要所有匹配的记录,您可以使用

 @current_marks = Mark.where student_id: @student.id

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM