0

Essentially I have an app usong Devise, i've a user model and an agenda model. Agenda 'belongs_to' user and user 'has_many" agenda, these are my db relationships. I can fire up IRB and get db data correctly user = User.first user.agendas and I will get a list of all posts that belong to that user My problem occurs upon signing in, the user is redirected to home#index but I get a NoMethodError in Home#index undefined method `agendas' for nil:NilClass I'm sure i'm missing something. Do I need an index method in my agenda controller also? ..app/views/home/index.html.erb

<h3>Home</h3>
<div class="row">
    <div class="span8">
        <% if @user.agendas.any? %>
        <h3>Agendas</h3>
        <ol class="agendas">
            <%= render @agendas %>
        </ol>
        <% end %>
    </div>
</div>

my home_controller.rb

class HomeController < ApplicationController
  before_filter :authenticate_user!

  def index
    @agendas = current_user.agendas.paginate(page: params[:page])
  end

My agenda controller just has a create and destroy stub for future code. its model /agenda.rb

class Agenda < ActiveRecord::Base
  attr_accessible :title
  belongs_to :user

  validates :title, presence: true, length: { maximum: 140 }
  validates :user_id, presence: true

  default_scope order: 'agendas.created_at DESC'
end
2
  • 1
    caught my myproblem ...home.html.erb should be current_user.agendas.any? May 3, 2012 at 17:16
  • but the agendas are not populating, anyone see any issues with display code? May 3, 2012 at 17:16

1 Answer 1

0

Your error is coming from this:

<% if @user.agendas.any? %>

and the error says that @user is nil. Your controller says:

def index
  @agendas = ...
end

I don't see @user being assigned a value in there. I don't think your authenticate_user! filter is setting @user either. So you could do this:

def index
  @user    = current_user
  @agendas = @user.agendas.paginate(page: params[:page])
end

And then:

<% if @user.agendas.any? %>
  <h3>Agendas</h3>
  <ol class="agendas">
    <%= render @agendas %>
  </ol>
<% end %>

You could also access current_user directly in your ERB:

<% if current_user.agendas.any? %>
  <h3>Agendas</h3>
  <ol class="agendas">
    <%= render @agendas %>
  </ol>
<% end %>

But keep in mind that you've already gone to the trouble of computing @agendas so why not just look at that and leave your controller alone?

<% if @agendas.present? %>
  <h3>Agendas</h3>
  <ol class="agendas">
    <%= render @agendas %>
  </ol>
<% end %>
1
  • Thank you for the answer, I found it. May 3, 2012 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.