Devise form within different view “undefined metho

2019-09-18 20:37发布

问题:

So I am trying to do pretty much the same thing as Devise form within a different controller

exactly Devise Login Form on another page

I have a helper module that has

def resource_name
  :user
end

def resource
  @resource ||= User.new
end

def devise_mapping
  @devise_mapping ||= Devise.mappings[:user]
end

but I am getting undefined method `[]' for nil:NilClass on the line

<%= f.email_field :email, :autofocus => true %></div>

I put <% raise resource.inspect %> in views/devise/sessions/new.html.erb

and I got RuntimeError in Home#index #User not initialized

<h2>Sign in</h2>

<%= form_for(resource, :as => resource_name, :url => user_session_path(resource_name)) do |f| %>
  <% raise resource.inspect %>
  <div><%= f.label :email %><br />
  <%= f.email_field :email, :autofocus => true %></div>

  <div><%= f.label :password %><br />
  <%= f.password_field :password %></div>

  <% if devise_mapping.rememberable? -%>
  <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
  <% end -%>

  <div><%= f.submit "Sign in" %></div>
<% end %>

<%= render "devise/shared/links" %>

and I also tried this for the helper module

def resource_name
  :user
end

def resource
  @resource = User.new
end

def devise_mapping
  @devise_mapping = Devise.mappings[:user]
end

In Home#index, I have the following

<div class="loginform" id="login">
  <%= render :file => "devise/sessions/new" %>
</div>

The error "undefined method `[]' for nil:NilClass" will be gone if views/devise/sessions/new.html.erb edits to be

<%= form_for(:user, :as => @user, :url => user_session_path(@user)) do |f| %>

but if put <% raise resource.inspect %> back in views/devise/sessions/new.html.erb

will still get #User not initialized>

In user.rb

devise :database_authenticatable, :registerable, :confirmable,
     :recoverable, :rememberable, :trackable, :validatable

In application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  helper :all
end

using 'rails', '3.2.11'

I am not sure why the helper module doesn't work the way it supposes be for resource. Can anyone help me to understand why? and why getting "undefined method `[]' for nil:NilClass" ?

Thank you in advance.

回答1:

I think this line

<%= form_for(:user, :as => @user, :url => user_session_path(@user)) do |f| %>

should be

<%= form_for(@user, :as => :user, :url => user_session_path(@user)) do |f| %>