无法注册('对象'方法的错误),无法登录('create'方法的错误)

时间:2011-12-01 15:22:16

标签: ruby-on-rails-3 authentication

当我尝试在本地主机中注册时,这是我得到的错误:

NameError in Users#new
Showing /Users/alonbond/rails_projects/sample_app/app/views/shared/_error_messages.html.erb where line #1 raised:
undefined local variable or method `object' for #<#<Class:0x007f90a3c32d60>:0x007f90a3bf83b8>
Extracted source (around line #1):

    1: <% if object.errors.any? %>
    2:   <div id="error_explanation">
    3:     <h2>
    4:       <%= pluralize(object.errors.count, "error") %>

这是“新”的代码

<h1>Sign up</h1>

<%= form_for(@user) do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <%= render 'fields', :f => f %>
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>  

我的第二个问题是当我尝试登录时(我之前已经注册):

NoMethodError in SessionsController#create
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]

这是'create'方法的代码:

def create
    user = User.authenticate(params[:session][:email], params[:session][:password])

    if user.nil?
      flash.now[:error] = "Invalid email/password combination."
      @title = "Sign in"
      render 'new'
    else 
      sign_in user
      redirect_back_or user
    end  
  end

for_for:

<%= form_for(:session, :url => sessions_path) do |f| %>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="actions">
    <%= f.submit "Sign in" %>
  </div>
<% end %>

1 个答案:

答案 0 :(得分:0)

使用@user将局部变量用于局部变量,使用flash[:error]作为flash消息。