3

Im building my first app using rails and also im trying to add some ajax functionality on it. I have a signup form in my root url in order to create users but i cant find a way to show my success message after a user has been created. I can see the json response correctly but not the flash message. Is there something im missing in my code?

# Controller

def create
  @user = User.new(user_params(CREATE_PARAMS))

  respond_to do |format|
    if @user.save
      @user.send_activation_email
      format.html { flash[:info] = "Success!!"
                    redirect_to root_url
      }
      format.json { render json: @user, status: :created, location: @user }
    else
      format.html { render "new" }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

# application.html.erb

<body>
  <div class="container">
    <div class="message-notification">
      <%= render 'shared/alert_messages' %>
    </div>
    <%= yield %>
  </div>
</body>

# shared/_alert_messages.html.erb

<% flash.each do |message_type, message| %>
  <%= content_tag(:div, message, class: "alert-message alert-message-#    {message_type}") %>
<% end %>

# Handling errors users.coffee
$(document).on "ajax:error", "form#new_user", (event, data, status, xhr) ->
  $("form#new_user").render_form_errors "user", data.responseJSON

$.fn.render_form_errors = (model_name, errors) ->
  form = this
  this.clear_form_errors()

  $.each errors, (field, messages) ->
    input = $('input[name="' + model_name + '[' + field + ']"]');
    input.closest(".form-group").addClass("has-error")
    input.parents(".form-group").append('<span class="help-block">'  + 
      $.map(messages, (m) -> m.charAt(0).toUpperCase() + 
      m.slice(1)).join("<br />") + "</span>")

$.fn.clear_form_errors = () ->
  this.find(".form-group").removeClass("has-error")
  this.find("span.help-block").remove()
adavia
  • 413
  • 5
  • 18
  • Duplicate of http://stackoverflow.com/questions/23967390/rails-flash-notice-via-ajax. Net net is that you can't have a "real" flash message because you aren't making a server request but you can simulate one. – steve klein Jun 12 '15 at 19:53
  • The problem here is that im not being redirected, thats why i cant see my flash message, which i dont know why – adavia Jun 12 '15 at 21:12
  • I respectfully submit that the problem is that you cannot render a flash message with an Ajax request. – steve klein Jun 12 '15 at 21:17

1 Answers1

0

I think you must put the flash[:info] in the json block like

format.json { flash[:info] = "Success!!" }

instead of putting it in the format.html

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Vikram
  • 67
  • 9