我开始使用rails,所以这是一个相当基本的问题。我正在尝试使用以下代码在主页中呈现登录表单(authlogic):
视图/家/ 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
视图/ 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"
模型/ 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
当我访问主页时,我得到:
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'
我做错了什么,我该如何解决?
非常感谢你的帮助。
答案 0 :(得分:2)
在您的代码中,当您访问与@user_session
相关联的new
操作时,正在创建user_sessions/new
;当您转到index
操作时,不会创建它。
当您从user_sessions/new
操作中呈现index
模板时,ERB / HAML正在查找@user_session
的实例,但找不到它,因此错误。
所以,你可以像这样实例化@user_session
:
#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|
...
或者,您也可以在index
操作本身中执行此操作,但最好将其与index
操作保持一致,而不是如上所述(例如,如果您想要的话)从其他一些动作渲染模板 - 然后你会不必要地复制代码)