The dreaded missing template error

631 views Asked by At

I've read everything I can find, and I'm still stumped.

I'm trying to use a before_filter to catch users who are not logged in, and send them to an alternative index page. The idea is that users who are logged in will see a listing of their own articles when they hit index.html.erb, users who are not logged in will be redirect to a showall.html.erb page that lists the articles but does not let them read them (and hits them with some ads).

I added a route:

resources :articles do
get "showall"
resources :comments
end

'Rake routes' shows a route article_showall. I have a partial _showall.html.erb in the views/articles folder (it only contains the text 'showall is working!'). If I render showall in another view (<%= render "showall" %>), it works fine.

This is the applicable part of my controller:

class ArticlesController < ApplicationController
skip_before_action :authorize, only: [:index, :show, :showall]
before_filter :require_user, :only => [:index]

def require_user
unless User.find_by(id: session[:user_id])
  render 'showall', :notice => "Please log in to read articles."
end
end

def index

@articles = current_user.articles

end

def showall
@articles = Article.all
end

When I run it (while not logged in), it get the following error:

Missing template articles/showall, application/showall with....etc

I'm stumped. Why can I render 'showall' in a view, but I get Missing Template error when I refer to it in my controller? Thank you in advance for any help!

3

There are 3 answers

0
chad_ On BEST ANSWER

David and user4703663 are right. Your problem is that you named the template to be a partial but are rendering it as a template. You could either remove the underscore from the file name and leave your code as it is, or leave the filename as it is and "render partial: 'showall'" from your index view.

edit: I should add that the missing template error should not instill dread in your heart. It's guiding you to your mistake, directly. Don't stress it and just try to remember what it meant next time. It's almost always a typo, or loading a partial but naming it as a template or vice versa, or forgetting a subfolder for a relative path or something like that. It's normal, and the interpreter spits those errors to help you, not to oppress you.

0
SeattleDucati On

Great, fixed that problem, and now it spits back
undefined method `each' for nil:NilClass

even though the 'showall' is nearly identical to 'index'.

SIGH

0
Aakash Aggarwal On

Replace

render 'showall', :notice => "Please log in to read articles."

with

render :file => '/partial/showall', :notice => "Please log in to read articles."