c.nj
c.nj

Reputation: 35

Rendering view from different controller NilClass Error

I'm trying to render a view in a different controllers view but I'm getting:

undefined method `each' for nil:NilClass

I'm rendering the view in 'views/users/show' as:

<%= render :template => 'groups/index' %>

The view itself is under 'views/groups/index':

<% @groups.each do |group| %>
  <li>
    <%= group.name %>
    <%= group.description %>
  </li>
<% end %>

And my groups controller for index looks like this:

def index
  @groups = Group.all
end

I think it's a problem with how i'm rendering the view since if I make an instance variable in my index controller and call it in the view it won't appear. There are entries in the Group table in my database.

Any help would be appreciated.

Thanks in advance.

Upvotes: 1

Views: 615

Answers (2)

Tucker
Tucker

Reputation: 659

Change:

<%= render :template => 'groups/index' %>

To:

<%= render 'groups/index' %>

and make sure the file name of your index action is _index.html.erb and not index.html.erb.

EDIT

When you render a view, you are only rendering the template, this does invoke a request on your index action. You must define @groups in your initial view's action.

Upvotes: 1

The F
The F

Reputation: 3714

I think it should be enough to replace the template: with a partial: parameter.

Try this:

<%= render partial: 'groups/index' %>

You will have to rename/copy groups/index.html.erb with groups/_index.html.erb

This only works for rendering a view, but will not implement the functionality of your GroupsController.

Edit

You will have to redefine the groups inside your UsersController

# UsersController
def index
  @groups = Group.all
end

Depending on how many times you will need to present all these groups to your user, this can become hard to maintain. If you use it frequently, consider adding

# i.e. ApplicationController
def groups
  Group.all
end

inside your ApplicationController (or some module you want to include in different controllers). Then you could call

# UsersController
def index
  @groups = groups
end

and still <%= render partial: 'groups/index' %>

Upvotes: 1

Related Questions