0

I am trying to use the link_to feature to link one view to another.

The view i am calling link_to is app/views/instructors/show.html.erb and that snippet of code looks like this (namely, the second to last line of it)

<% provide(:title, @instructor.login) %>
<% courses = Course.where(:instructor_ID => @instructor.id) %>
    <div class="span2">
      <h1 align=center ><%= @instructor.login %></h1>
      <%= link_to "Add course", new_course_path(:instructor_ID\
                => @instructor.id), :class => "btn" %>
        <br>
        <br>
        <%= link_to "Remove course", delete_course_path(courses), :class => "btn"%>
    </div>

The view I am trying to link to is is app/views/courses/show_all.html.erb and looks like this:

<% @courses.each do |course| %>
  <tr>
    <td><%= course.course_name %></td>
    <td><%= course.instructor_ID %></td>
    <td><%= link_to 'Show', course %></td>
    <td><%= link_to 'Edit', edit_course_path(course) %></td>
    <td><%= link_to 'Destroy', course, :method => :delete, :data => { :confirm => 'Are you sure?' } %></td>
  </tr>

delete_course_path routes to app/views/courses/show_all.html.erb shown above. When I try the code above, I get the following error:

undefined method `each' for nil:NilClass

At this line:

<% @courses.each do |course| %>

Any ideas what i'm missing in my link_to?

Layla
  • 347
  • 1
  • 6
  • 13

2 Answers2

0

This means that @courses is nil. Did you set it in your show_all action of your controller? E.g.

def show_all
  @courses = Course.all
end

Also, in your show view, you set courses to a collection of Course objects, but your "Remove course" link looks like you only want to delete one course. Why do you use the delete_course route to link to your show_all view?

Sven Koschnicke
  • 6,523
  • 2
  • 34
  • 49
  • Thanks that worked. Pardon my lack of knowledge on the topic but does that mean that every view needs a controller method to go along with it? – Layla Nov 23 '12 at 07:58
  • In most cases, there should be a controller method for each view. By using the `render` method in a controller action you can specify another view to be rendered, though. Or redirect to another page, see the scaffolded delete, update or create methods of the controller for example. – Sven Koschnicke Nov 23 '12 at 08:00
0

In your show_all action, you should define a @courses instance variables. This is

<% courses = Course.where(:instructor_ID => @instructor.id) %>

not passed to show_all.html.erb.

An instance variables is a variable passed from action of controller to the view corresponding.

I suppose when you show page of instructor, your route will like this: /instructors/:id, so maybe in your show_all action of instructor controller, you need something like:

def show_all
  @courses = Course.where(instructor_ID: params[:id])
  render 'courses/show_all'
end
Thanh
  • 8,219
  • 5
  • 33
  • 56