Devise Registration form on any page

2019-03-20 12:53发布

问题:

I'm trying to allow users to sign up for the site on my home/landing page. I've duplicated the devise registration form into my landing page view-

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div><%= f.label :first_name %><br />
  <%= f.text_field :first_name %></div>

  <div><%= f.label :last_name %><br />
  <%= f.text_field :last_name %></div>

  <div><%= f.label :profile_name %><br />
  <%= f.text_field :profile_name %></div>

  <div><%= f.label :email %><br />
  <%= f.email_field :email %></div>

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

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

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

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

And I've also added the helper methods in my application_controller.rb so that I properly define the resource-

class ApplicationController < ActionController::Base
  protect_from_forgery
  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

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

However I'm still getting the error undefined local variable or method resource'for #<#:0x007fa816b4b750>`

What am I missing here to properly render a REGISTRATION form on my home landing page?

回答1:

You need to declare those controller methods as helper methods to access them from the views:

helper_method :resource, :resource_name, :devise_mapping

Just add that line inside your ApplicationController after the methods are defined.

You'll notice that the link you provided actually mentions to put this code in the application helper, not the controller... You can avoid this helper_method declaration if you do it that way.