Search code examples
ruby-on-railscoffeescript

Converting application JS to CoffeeScript


I have created a nested form in my rails app with help of nested_form_for gem. I am tried to convert application.js to application.coffee. But I faced following issue for nested_form_for gem:

couldn't find file 'jquery_nested_form' with type 'application/javascript'

Following is my application.coffee content:

#= require jquery
#= bootstrap.min.js
#= owl.carousel.min.js
#= require jquery_ujs
#= require jquery-ui
#= require jquery_nested_form
#= require_tree ./controllers
#= require_tree .

Solution

  • You've got a couple of problems here.

    First, you're missing some "requires" in lines 2 and 3 of your application.coffee. These lines:

    #= require jquery
    #= bootstrap.min.js
    #= owl.carousel.min.js
    

    should become:

    #= require jquery
    #= require bootstrap.min.js
    #= require owl.carousel.min.js
    

    Second, your couldn't find file 'jquery_nested_form' error is most likely because the nested_form gem isn't currently in your bundle. Make sure that you've got a line like:

    gem 'nested_form'
    

    in your Gemfile, and then run:

    $ bundle install
    

    in your Rails root directory.

    Finally, just as a general point of Ruby on Rails style, it's rarely necessary or helpful to convert application.js to application.coffee. This file is just a manifest that tells Rails which javascript/coffeescript files to include in the compiled application.js. Since you're not generally advised to add code to this file anyways, it doesn't seem like there'd be much value in converting it to coffeescript. It's totally fine to leave this file as javascript, and write all your code in separate coffeescript files. From the default file comments:

    // This is a manifest file that'll be compiled into application.js, which will include all the files
    // listed below.
    
    // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
    // compiled file. JavaScript code in this file should be added after the last require_* statement.