4

In my rails application I have dragdrop.js.erb in /assets/javascript folder. In which I have an ajax block which should render a partial in a div with an on click action. I tried many things but I can't get it working. Any help would be appreciated.

Here is the code:

 $.ajax({  
   type: "GET",    
   url: "<%=  Rails.application.routes.url_helpers.cookbooks_path %>",
   success: function(resp){
  $("#property").load("<%= escape_javascript (render :partial => 'recipes/package_form') %>") 
   }
atw
  • 5,428
  • 10
  • 39
  • 63
Bibin Wilson
  • 506
  • 6
  • 15
  • post related code that you have tried, so that we can help you – RAJ Aug 19 '14 at 11:44
  • Whats the error/exception? Anyways, any special reason to keep `.js.erb` into `assets/javascript` instead of `app/views`? – RAJ Aug 19 '14 at 12:04
  • `undefined method `render' for # (in /home/cookmaster/workspace/test/app/assets/javascripts/dragdrop.js.erb)` – Bibin Wilson Aug 19 '14 at 12:05

2 Answers2

8

Your problem is that you are trying to use render in assets, however, render is not available in assets

You should move your .js.erb file to an appropriate directory under app/views


Here are some other similar question:

  1. Rendering A Partial In Assets
  2. Rails JS ERB File Cannot Find Method Render
  3. When rendering a partial from tasks.js.coffee.erb - undefined, render
Community
  • 1
  • 1
RAJ
  • 9,697
  • 1
  • 33
  • 63
5

Asset Pipeline

Firstly, you need to make sure that you don't use any Rails dynamic path helpers in your javascript directly.

The issue is that if you pre-compile your asset pipeline, you'll typically find these dynamic path helpers won't work correctly. Although there's nothing "wrong" with it - I tend to keep Rails back-end code completely separate from the front-end, as to ensure the versatility of the application:

#app/assets/javascripts/application.js
$(document).on("click", ".element", function(){
   $.ajax({  
     type: "GET",    
     url: "/cookbooks"
  });
});

This will send a "naked" Ajax request (no params / body) to your controller backend:

#app/controllers/cookbooks_controller.rb
Class CookbooksController < ApplicationController
   def index
      @cookbooks = Cookbook.all
      respond_to do |format|
        format.html
        format.js #-> loads /views/cookbooks/index.js.erb
      end
   end
end

The trick here is that you can now populate your index.js.erb file with the params necessary to render the partial:

#app/views/cookbooks/index.js.erb
$("#property").html("<%=j render :partial => 'recipes/package_form' %>") 

--

This should work for you

Richard Peck
  • 76,116
  • 9
  • 93
  • 147