Skip to content
Advertisement

How to trigger a JS code once when a new model is created in rails?

I’m trying to have an ‘Achievement Unlocked’ JS animation play on my show page when someone creates a new cocktail model. So it should only play once and never again on that particular page. I’m kinda stuck on how to do that without creating a separate table for ‘Achievements’ in my DB. Does anyone have a simple solution? Here’s my controller (the NUM, @num, and @num2 are variables I created to figure out a solution, feel free to disregurad):

JavaScript

My HTML (The first div is the animation’s html. My current code allows the animation to play more than once in all cocktail show pages that were created after the 7th cocktail) :

JavaScript

Advertisement

Answer

Pass that info in params (the info that it is first or not) in params in the redirect after create and check in render view if params[:first_time].exists? and execute JS in that case. You did not need to allow it in params as it was not something being “posted” from view to controller. NameError means you did not define it and that happened because you were sending @num2 = @num2 (key-value pair in params hash) and u had not defined num2’s value. You could do num2: “I am num2” or anything and that would work 🙂

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement