FNGR FNGR - 1 year ago 84
Javascript Question

Update Devise user field via jQuery partial form

I'm a real rails beginner trying to build a little app. So I got rails 4.2.5 and Devise for my User authentication. I've added two extra fields (username, city) to the user model. Everything works fine.

I got a partial at the top of my app, that is opened with jquery by clicking on a button on every page. This partial should include a input field, where the user can edit his city (via AJAX?). After submitting, the city should be changed and the page reloaded.

And now I'm not sure how to achieve this and what is the way to go. I just need a small guide that helps me to get this done! Because devise by default doesn't generate controllers and doesn't uses the normal paths, I'm a little bit lost with my small experience in rails.

Thank you very much in advance! :)

Answer Source

So, big thanks to Hieu Pham! I figured out how to get it working with your steps. But I had to modify them a little bit, but now it's working :) So, here it is for everybody else who want to know:


devise_scope :user do
  patch "update/:id", to: "registrations#update_city", as: "update_city"


class RegistrationsController < Devise::RegistrationsController

  def update_city
    @user = current_user
    if @user.update_attributes(user_params)
      respond_to do |format|
        format.js {render inline: "location.reload();" }
      flash.now[:error] = "Could not save client"


  def user_params


my form partial

<%= simple_form_for @user, url: update_city_path(@user), remote: true do |f| %>
  <%= f.input :city, placeholder: t('.yourcity') %>
  <%= f.button :submit, t('.submit') %>
<% end %>

Now it's working fine :) I know, i need to add better responds on save, but that was just for debugging!