3

I'd like to execute a jQuery script while rendering an action in my rails controller.

To be more precise, I have this function in my users controller ...

def create
    @user = User.new(user_params)
    if @user.save
      # Successful save
    else
      render action: "new", layout: "signup"
    end
end

... and I want to add a class to a specific element in my new.html.erb file. I need to do that when rendering only because I don't want the class to be added beforehand.

How can I do that?

4
  • stackoverflow.com/questions/6705333/… Something like this? Commented Jul 27, 2017 at 22:11
  • 1
    This seems like an XY Problem to me. You want an HTML element to have (or not have) a class based on some condition? Executing a JQuery script when rendering does not strike me as the way to go about such a thing. Commented Jul 27, 2017 at 22:30
  • Well in the context of Rails, I don't know If I can call this a condition. I'd like my element to have (or not have) a class depending on the action rendering this particular element. Commented Jul 27, 2017 at 22:36
  • 2
    in your new.html.erb file, you can access the params[:action] which will tell you if you submitted the form and the user failed to save (if you are rendering new under the params[:action] create, it means something went wrong). Option 2: setting @some_variable in the create action and test it in the view. Option 3 check for @user.errors, if there are errors in the @user object then it means the save was not successful. In conclusion, there is no need to use jQuery for that, you have to use a way to differentiate the new action from the (failed) create action. Commented Jul 27, 2017 at 23:38

0

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.