Rails 3: Instance variable inaccessible in .js.erb file -


i'm trying build simple page, need generate dynamic javascript photo gallery. intuitively simple, i'm struggling greatly. in controller building list of photo @photos, need iterate out javascript each photo in photo.js.erb file.

however, whenever reach .js.erb file, @photos variable becomes nil... missing?

controllers/photos_controller.rb file:

class photoscontroller < applicationcontroller   layout "application_photos"   def category     @photos = ...(generates collection of photos)...   end end 

views/photos/category.html.haml file:

= content_for :head   // @photos still initialized @ point   = javascript_include_tag "photos"  // partial loads more markup, it's inconsequential. = render :partial => 'default_slideshow' 

javascripts/photos.js.erb file:

jquery(function($){     // throws nilclass error     <% puts 'photos: ' + @photos %> }); 

i know question has been asked dozen times, none of accepted answers worked me. suggestions appreciated.

you need send js request server in order have access instance variable. this

$(function($){   $.ajax({     type: "get",     url: "..."     })    }); 

in views/photos/category.js.erb file:

alert("<%= j @photos %>") 

or can same using gon gem.

app/views/layouts/application.html.erb

<head>  <title>some title</title>  <%= include_gon %>  <!-- include action js code -->  ... 

you put in action of controller:

@your_int = 123 @your_array = [1,2] @your_hash = {'a' => 1, 'b' => 2} gon.your_int = @your_int gon.your_other_int = 345 + gon.your_int gon.your_array = @your_array gon.your_array << gon.your_int gon.your_hash = @your_hash  gon.all_variables # > {:your_int => 123, :your_other_int => 468, :your_array => [1, 2, 123], :your_hash => {'a' => 1, 'b' => 2}} gon.your_array # > [1, 2, 123]  gon.clear # gon.all_variables {} 

access varaibles javascript file:

alert(gon.your_int) alert(gon.your_other_int) alert(gon.your_array) alert(gon.your_hash) 

hope helps


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -