Question

In my rails app, if I go to localhost:3000/users/edit to update user

<h2>Edit <%= resource_name.to_s.humanize %></h2>

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %>
  <%= devise_error_messages! %>

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


  <div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br />
  <%= f.password_field :password, :autocomplete => "off" %></div>

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

  <div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br />
  <%= f.password_field :current_password %></div>

  <div><%= f.submit "Update" %></div>
<% end %>

<h3>Cancel my account</h3>

<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), :data => { :confirm => "Are you sure?" }, :method => :delete %></p>

<%= link_to "Back", :back %>

It 's alright, but if I move this code ((or render this view) to another view of another controller it 'll have an error :"undefined local variable or method `resource' for #<#:0x3b27478>" I don't know how to fix it, any help really appreciated.

Was it helpful?

Solution

resource is a variable set by the Devise gem. In order to move the above code somewhere else, it means that you will have to take care of setting the resource variable yourself.

Basically a rails form_for wants to take the instance of the object you want to create / edit.

<%= form_for instance_object ...

In your case you'll need to first fetch the user you want to edit (or use current_user) and then give it to the form_for helper method:

<%= form_for current_user ...

or by setting the @user instance variable in your controller first:

def new
  @user = User.new
end

def edit
  @user = User.find(some_id)
end

Then in your view:

<%= form_for @user ...

Don't forget to replace all the resource occurences by your instance variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top