TomMElack
TomMElack

Reputation: 23

Pass local rails variable to javascript to partial

I'm giving up my search, I normally try to figure these things out on my own but I'm struggling hard and I just want this to work

I have the link_to seen below where @puser is the user of the profile I'm currently viewing.

<%= link_to 'Request', new_or_edit_relationship_path(nil), :remote => true, :locals => { :puser => @puser} %>

This in turn calls new_relationship_path which is a .js.erb file seen below

alert("<%= escape_javascript(puser.id) %>")

Why won't this work!? It's saying the puser variable or method is undefined. This works perfect if I was to just render a partial passing in the locals but no. Javascript doesn't want to play nice

Could anyone help explain why me or the program is stupid?

Upvotes: 1

Views: 1104

Answers (1)

Chris Peters
Chris Peters

Reputation: 18090

When you do a link_to as remote, the user is starting an entirely new request when they click the link. So passing a local means nothing to the new request. (The local doesn't exist any more on the new request.)

So in order for the @puser to exist on the new request, you need to pass the id for that @puser via the URL (whatever you have going on for new_or_edit_relationship_path). The new request needs to look up the puser by that id, and then it can use it in the JS alert().

Hope that helps and is a little clearer than mud.

Upvotes: 1

Related Questions