Pass local rails variable to javascript to partial

本秂侑毒 提交于 2019-12-24 16:39:00

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12342058/pass-local-rails-variable-to-javascript-to-partial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!