I am stuck in an (apparently) simple problem. In my event_controller I have the i_like_it action:
def i_like_it @event = Event.find(params[:id]) ... # logic respond_to do |format| format.js end end
In my case "i_like_it" is called with :method => PUT (it is an Ajax call, "i_like_it.js.erb" will be returned as a script and it wil be executed on the browser.)
I would like render a Javascript file with a different name (not i_like_it.js.erb) , but I haven't found any option in the Rails API docs.
respond_to do |format| format.js { render ??? } end
Rails can render vanilla JavaScript with :js option, but I don't want use Javascript in the controller.
Do you have any suggestion ?
Thank you, Alessandro DS
To avoid multiple server requests, group your JavaScript files into one. Whatever you use for performance, try to minify JavaScript to improve the load time of the web page. If you are using single page application, then group all the scripts in a single file.
To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.
JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body. JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked.
If you do:
respond_to do |format| format.js { render :action => "different_action" } end
it will load RAILS_ROOT/app/views/your-controller/different_action.js.erb instead.
The format.js block just ensures that if it's a .js request, you have the proper headers set by default and it looks for .js.erb or .js instead of .html.erb by default.
You can also use render :file to render any arbitrary file on the file system that happens to have JS in it, or you could use any of render's other usual options. There are a few of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With