0

I'm using Rails 4. I have the following file:

// apps/assets/javascripts/products.js.erb

var getColoursAndMaterialsData = function(onSuccess)
{
    var fd = formdata();

    $.post( '<%= data_products_path(:format => :json) %>', fd )
    .done(function(data)
    {
        onSuccess(data);
    });
};

When products.js.erb is included in a .html.erb file I get the error:

undefined method `data_products_path'

clearly routes prefix 'data_products_path' isn't being pre-processed. I was under the impression that giving the products.js the .erb extension would coax the pre-processor.

The same exact same code works when between the <script type="text/javascript"></script> tags in the .html.erb file. The relevant part of my routes.rb looks like this:

resources :products do
    collection do     
        post 'data'
    end
end

Is there something else I need to do?

Paul Grenyer
  • 1,713
  • 3
  • 30
  • 51
  • The error message indicates that your template is being processed but rails doesn't know the data_products_path method. Can you show your config/routes.rb file? – fkoessler Dec 21 '14 at 08:12
  • I should probably have mentioned that the exact same code works when put directly the . I'll update the question with this and add the relevant part of routes.rb. – Paul Grenyer Dec 21 '14 at 08:20

1 Answers1

1

I dont think it will work just by adding .erb extension. why not do a simple jQuery ajax post request...

use dataType: "json" to make sure you get json response and instead of using url helpers just specify the url.

http://api.jquery.com/jquery.post/

The link below answers your question

Using a Rails helper method within a javascript asset

Community
  • 1
  • 1
Aditya Shedge
  • 386
  • 1
  • 7
  • Thanks! Adding '<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>' to the top of the .js.erb file, as per the link you posted, fixed the problem. – Paul Grenyer Dec 21 '14 at 08:38