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::Tem开发者_JAVA技巧plate::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_session
is being created when you visit the new
action that is connected to user_sessions/new
; it is not created when you go to the index
action.
When you render the user_sessions/new
template from the index
action, ERB/HAML is looking for an instance of @user_session
and cannot find it, hence the error.
So, you could instantiate @user_session
like this:
#Note: The <%%> is ERB code (please adjust it for the syntax used in HAML)
<% @user_session = UserSession.new if @user_session.nil? %>
= form_for @user_session, :url => {:action => "create"} do |f|
...
Or, you can also do it in the index
action itself, though it would be better to keep it out from the index
action 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)
精彩评论