grabury
grabury

Reputation: 5559

Rails update model without leaving page

What would be the best way to update a record and display a flash success notice without leaving the page?

Here is part of my code but it redirects back to root path:

View

      <%= form_for @user, url: record_testimonial_path(@user) do |f| %>  
        <%= f.text_area :testimonial %>
        <%= f.submit "Submit"%>
      <% end %>

Controller

def record_testimonial
  @user.update_attribute(:testimonial, params[:user][:testimonial])
  flash[:success] = "Thank you!"
  redirect_to root_path
end

Upvotes: 0

Views: 617

Answers (2)

Stephan1990
Stephan1990

Reputation: 465

You can redirect back:

redirect_to :back, flash: { success: t('flash.thank_you') }

Or you have to do it via remote:

<%= form_for @user, url: record_testimonial_path(@user), remote: true do |f| %>  
  <%= f.text_area :testimonial %>
  <%= f.submit "Submit"%>
<% end %>

And in the controller:

def record_testimonial
  if @user.update_attribute(:testimonial, params[:user][:testimonial])
    respond_to do |format|
      format.js { render 'record_testimonial', layout: false }
    end
  else
    render nothing: true # This will silently fail. Probably not intended.
  end      
end

And then the record_testimonial.js.erb:

$('#some_id').html('<%= j render "some_partial", user: @user %>');

These are the most common and I would say sensible ways. If you use ajax don't forget to manually display the flash message, should be 1 line of JS.

Upvotes: 2

Florian
Florian

Reputation: 3366

Best way to avoid a page refresh completely would be to set the form to use :remote => true like this

<%= form_for @user, url: record_testimonial_path(@user), :remote => true do |f| %> 

and then respond accordingly in the controller:

def record_testimonial
  respond_to do |format|
    if @user.update_attribute(:testimonial, params[:user][:testimonial])
      render :success
    else
      render :error
    end
  end
end

You would need a corresponding template for success and error here, with which to handle the displaying of a success or error message.

For further info, look here.

Upvotes: 0

Related Questions