I am getting started with rails, so this is a fairly basic question. I am trying to render a login form (authlogic) in the homepage, using this code:
views/home/index.html.haml:
%p
This is the home page...!
- if current_user
- else
= render :template => 'user_sessions/new'
user_sessions_controller:
class UserSessionsController < ApplicationController
before_filter :require_no_user, :only => [:new, :create]
before_filter :require_user, :only => :destroy
def new
@user_session = UserSession.new
end
def create
@user_session = UserSession.new(params[:user_session])
if @user_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default user_controls_url
else
render :action => :new
end
end
def destroy
current_user_session.destroy
flash[:notice] = "Logout successful!"
redirect_back_or_default home_url
end
end
views/user_sessions/new.html.haml
= form_for @user_session, :url => {:action => "create"} do |f|
= f.error_messages
%div
= f.label :login
= f.text_field :login
%div
= f.label :password
= f.password_field :password
%div
= f.check_box :remember_me
= f.label :remember_me
%div
= f.submit "Login"
models/user_session.rb
class UserSession < Authlogic::Session::Base
def to_key
new_record? ? nil : [ self.send(self.class.primary_key) ]
end
httponly true
secure true
end
When I visit the homepage, I get:
ActionView::Template::Error (undefined method `model_name' for NilClass:Class):
1: = form_for @user_session, :url => {:action => "create"} do |f|
2: = f.error_messages
3: %div
4: = f.label :login
app/views/user_sessions/new.html.haml:1:in `_app_views_user_sessions_new_html_haml___182031841_97682750'
app/views/home/index.html.haml:6:in `_app_views_home_index_html_haml__679857083_97787190'
What am I doing wrong, and how do I fix it?
Thanks a lot for your help.
In your code,
@user_sessionis being created when you visit thenewaction that is connected touser_sessions/new; it is not created when you go to theindexaction.When you render the
user_sessions/newtemplate from theindexaction, ERB/HAML is looking for an instance of@user_sessionand cannot find it, hence the error.So, you could instantiate
@user_sessionlike this:Or, you can also do it in the
indexaction itself, though it would be better to keep it out from theindexaction and instead do it as above (eg. what if you want to render the template from some other action as well – then you would be duplicating code unnecessarily)