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?
This means that @courses
is nil. Did you set it in your show_all
action of your controller? Eg
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?
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
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.