简体   繁体   中英

Ruby on Rails routes prefixes not pre-processing in .erb.js file

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM