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?
new.html.erbfile, you can access theparams[:action]which will tell you if you submitted the form and the user failed to save (if you are renderingnewunder theparams[:action]create, it means something went wrong). Option 2: setting@some_variablein the create action and test it in the view. Option 3 check for@user.errors, if there are errors in the@userobject 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 thenewaction from the (failed)createaction.