0

So I've been searching for an answer to this, but I've been having a lot of trouble. I'm trying to have a form_for in rails that goes to the create action in the User controller, which updates the color of the submit button depending on whether it fails submitting or not. Here is my code, some of which is directly from a tutorial I found online:

class UsersController < ApplicationController

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

    respond_to do |format|
      if @user.save
         format.html { redirect_to @user, notice: 'User was successfully created.' }
         format.js   {}
         format.json { render json: @user, status: :created, location: @user }
      else
         format.html { render action: "new" }
         format.json { render json: @user.errors, status: :unprocessable_entity }

      end
end

private

def user_params
  params.require(:user).permit(:email)
end

And here is my create.js.coffee.erb file.

if(!isValidEmailAddress($('#e_submit').val())){
        $('.button').text("Invalid Email");
        $('.button').animate({"background-color":"#FFBF00"},300);
        $('.button').hover(function(){
        $(this).css("background-color","#FFBF00");
        }, function(){
            $(this).css("background-color","#FFBF00");
        });
        $('#e_submit').css("box-shadow","0 0 0px rgba(0,0,0,0)");
        $('#e_submit').val("");
    }

Basically, I want different js events to happen depending on the submitted information, and I don't know how to do this in rails.

1 Answer 1

2

You could check if there are any errors on @user in your js template to know if save is success or not, create.js.coffee.erb:

<% if @user.errors.empty? %>
  # successfully saved
<% else %>
  # failed to save
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

In this case, would it still make sense to put the if, else in the controller?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.