Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a rails variable into a js function

Apologies -- I'm a newbie using Ruby on Rails. Still a little confused about how it works.

Right now, in my view, under my scroller div, I have this code:

#scroller
 -@other_images.each do |img|
  .thumbnail_wrapper
    .thumbnail_image
      =image_tag img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(img.id);"

@other_images is a variable that holds all the thumbnail images I want to display on the page. Clicking on one will refresh a div elsewhere with its own big image.

the corresponding js function is:

:javascript
 function replaceImg(id){
  var url = '/images/refresh/' + id;
  new Ajax.Updater('content_image', url);
 }

This works if I just write in a valid url. But passing the param "id" into the js function does not work. I'm at a loss... what am I missing?

How do I pass this rails variable -- img --- into my js? It's just stuck in that loop.

Any help would be really appreciated.

like image 748
mtay Avatar asked Nov 27 '10 09:11

mtay


1 Answers

Try this:

img.image.url(:thumbnail), :class => 'button' , :onClick => "replaceImg(#{img.id});"

The #{...} construct executes the ruby code within the curly brackets and replaces the entire construct with the result. Can be used anywhere you want to replace part of a string with some content from a ruby variable or method.

like image 163
harald Avatar answered Oct 23 '22 06:10

harald