Passing instance variable to js.erb file (Rails 3 / jQuery)

17,396

Solution 1

You access the information in your *.js.erb-files just like in your *.html.erb-files, using @users or other instance variables declared in the controller:

$("#<%= @user.id %>_action").toggle();

Solution 2

there's an excellent gem called gon that might simplify and organize things quite a bit: https://github.com/gazay/gon/blob/master/README.md

Share:
17,396
neon
Author by

neon

Updated on June 18, 2022

Comments

  • neon
    neon almost 2 years

    I have an "index.html.erb" file with the following:

    <%= render @users %>

    This renders "_user.html.erb" and outputs a button for performing a certain action on each user:

    <%= link_to "action", action_path(user), :id => "#{user.id}_action", :remote => true) %>

    I've set up my User controller to respond to the AJAX request by looking at "action.js.erb".

    In order to perform javascript methods on particular users within the partial, and I'd like to know how instance variables from my partial (such as user.id) can be passed into or accessed within the js.erb file, for instance:

    $("#{@user.id}_action").toggle();
    
  • neon
    neon almost 13 years
    please see edit. declaring @user.id within the js.erb as such isn't being recognized.
  • neon
    neon almost 13 years
    awesome. works with a minor edit to declare the css id using the "#" prefix. (please make the edit in your answer, it won't let me do it). thanks!
  • zx1986
    zx1986 over 7 years
    I got nil on @user or @whatever.
  • Felipe Maion
    Felipe Maion about 7 years
    Perfect!! Exactly what I was looking for!!