ruby-on-railsrubydeviserailsapps

Make the Devise new user form created with railapps a partial to re use it


I've created a new app with the Rails App composer with Devise and Pundit. The composer has created a form to create new users (devise/registrations/new.html.erb) which i would like to make a partial so i can put it on other pages. The form is

  <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :role => 'form'}) do |f| %>
    <h3>Sign up</h3>
    <%= devise_error_messages! %>
    <div class="form-group">
      <%= f.label :email %>
      <%= f.email_field :email, :autofocus => true, required: true, class: 'form-control' %>
    </div>
    <div class="form-group">
      <%= f.label :password %>
      <%= f.password_field :password, class: 'form-control' %>
    </div>
    <div class="form-group">
      <%= f.label :password_confirmation %>
      <%= f.password_field :password_confirmation, class: 'form-control' %>
    </div>ate_field :date_of_birth, class: 'form-control' %>
    </div>
     <%= f.submit 'Sign up', :class => 'button right' %>
  <% end %>

if i put this into a partial and try to render it on another page i get

undefined local variable or method `resource

and that's obviously because in my controller i didn't define anything. Problem is i can't find the controller or what resource should be in the other controller so that i can re-use this.


Solution

  • The resource method you are looking for is located here

    resource seems to be defined by an instance variable with the name of the actual resource you're using devise with.

    So, if you use devise for the users resource you should define resource as User.new on the controller you want to render that partial, and mark it as helper_method so it may be used in views, or just define it straight in the helper.

    Alternatively, you can just inherit DeviseController which already includes the resource definition and other useful methods as well.