简体   繁体   中英

Rendering Error Messages in Rails Form with Javascript

I've got a form that should render error messages but I'm not sure how to render the error messages since my form is being displayed with Javascript after clicking a button. I'm using Devise for the registration which is working just not displaying the error messages. I'm using Rails 4.

This is the code that hides the register button after it's clicked and shows the form:

<script type="text/javascript">
    $(function() {
        $('#prelaunchbutton').click(function() {
            $('#prelaunchregistrationbutton').fadeToggle('slow');
            $('.prelaunchhide').fadeToggle('slow'); 
            return false;
        });     
    });
</script>

Here is the Devise registration form (Shortened for brevity):

    <div class="prelaunch_preregisterbutton" id="prelaunchregistrationbutton">  
                <%= link_to image_tag("pre-register.png", :border=>0), '#', id:'prelaunchbutton' %> 
    </div>  
    <div class="span10 offset1 prelaunchhide">
            <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :class => "form-inline")  do |f| %>
    ...
<% end %>   
    </div>

Here is the Devise registration controller:

class RegistrationsController < Devise::RegistrationsController
  before_filter :authenticate_user!
  respond_to :html, :json

  def new
  end

  def create
    @user = User.new(user_params)
    @user.build_store(store_params)
    if @user.save
      UserMailer.preregister_confirmation(@user).deliver
      sign_in @user
      redirect_to prelaunch_gear_path, :flash => {:success => "Welcome"}
    else
      render root_path
    end
  end

  ...

  protected

  def after_update_path_for(resource)
    user_path(resource)
  end

  private 
  def user_params
     params.require(:user).permit(:firstname, :lastname, :email, :password)
  end

  def store_params
    params.require(:store).permit(:storename)
  end

end

You might look into using toastr for displaying javascript notifications.

Here's an SO question I answered before that may help set it up: Rails 4 - Toaster notifications rather than flash notifications -- you would just need to make your flash notification be flash.now[:toastr] and then be sure to call the initializer for that in the JS returned by the AJAX request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM