1

This is the code for my side bar. When a user clicks on one of the links, the js.erb file is called, but I don't know how to make the js.erb file be able to differentiate which link the user clicked on. My idea is to use an id, so basically pass the instance variable to the js.erb file. This is how I think it might be done, but I'm not sure at all.

<li>
    <%= link_to 'User Details', '/dashboard', :id => 'User Details', remote: true %>
</li>
<li>
    <%= link_to 'Projects', '/dashboard', :id => 'Projects', remote: true %>
</li>

There's the js.erb file that's run with this code:

<% if :id == 'User Details' %>
    $('#ajax').html("<%= escape_javascript(render :partial => 'users/edit', :locals => { :user => @user } ) %>");
<% elsif :id == 'Projects' %>
    $('#ajax').html("<%= escape_javascript(render :partial => 'projects/index', :locals => { :projects => @projects } ) %>");
<% end %>

What am I doing wrong or how should I pass some sort of flag or id to the js.erb file so that I can show the correct information?

Jack
  • 5,264
  • 7
  • 34
  • 43

1 Answers1

1

I'm not sure if you understand how websites work. Ruby is a server-side language, it is executed and html + js are sent to the web browser. JS files are (in most cases) executed just once on asset compilation/first run and never get updated again.
So there's no way to refer to Ruby code from js on the runtime as you are doing. Also you're using illegal characters in id attributes, see What characters are allowed in DOM IDs?

Back to ruby/js thing.

You may want to request a partial via ajax, passing an id attribute

$('#ajax').load('<%= here_put_helper_method_to_some_path %>');

And then in ProjectsController#index render what you wish (based on current user for example).

Also - a good rule is to first make things work without ajax and then add ajax calls.

Community
  • 1
  • 1
Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63