Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I render via CoffeeScript in Ruby on Rails 4

I was trying to solve this problem for a while with no result. I've wanted to pass variables and load a render into a div using CoffeeScript in rails 4. (I'm using SpreeCommerce platform).

view:

<%= link_to taxonomy.name,root_path+'t/'+tid, {class: "uno", remote: true} %>

controller:

  respond_to do |format|
    format.html
    format.js  # menu.js.coffee.erb
  end

menu.js.erb.coffee:

$('div#productos').html("<%= escape_javascript(render :partial => /shared/products) %>")

I'd like to load the page '_products.erb.html' and the partial processes the variables that I give it. As soon as I know, view and controller are ok, the problem is in menu.js.erb.coffee

Any help will be apreciated!

ADDITIONAL:

I've modified the extension to .js.coffee.erb. When I try to run the app, it shows me:

"undefined method `render' for #<#:0xa70317c>"

I tryied using <%= raw escape_javascript( render :partial =>... almost always "render" method give me problems.

NEW INFO:

I added gem 'coffee-script' to the Gemfile (then 'bundle install'). Now, when I click the link_to, it shows me into the HTML <%= escape_javascript(render :partial => /shared/products) %> as a text instead of loading the "partial"... any suggestion please?

like image 645
Ivan Carrasco Quiroz Avatar asked Mar 11 '26 10:03

Ivan Carrasco Quiroz


1 Answers

I wrote a post about this after struggling through the same problem.

You need to:

  • Name it menu.js.coffee. Suffixing .erb causes it not to be evaluated as CoffeeScript.
  • Use raw to escape it.

I used these two on my website. Here's how it looks:

<%= raw render 'path/to/menu.js.coffee' %>

It still processes ERB within your CoffeeScript.

like image 105
ashes999 Avatar answered Mar 13 '26 00:03

ashes999