1

I am trying to access a javascript variable in js.erb file inside erb tag. for example

my_variable = window.location.pathname.split("/")[2];

@project = Project.find(my_variable)

So is there a way to pass 'my_variable' in the 'find' helper.

Fakhir Shad
  • 1,071
  • 8
  • 20
  • Possible duplicate of [Passing variable from Javascript to Ruby on Rails](http://stackoverflow.com/questions/19057067/passing-variable-from-javascript-to-ruby-on-rails) – Brad Werth Nov 20 '15 at 09:40
  • or http://stackoverflow.com/questions/15422497/how-to-use-javascript-variables-in-ruby or http://stackoverflow.com/questions/4959770/how-to-pass-a-javascript-variable-into-a-erb-code-in-a-js-view or... – Brad Werth Nov 20 '15 at 09:41
  • 2
    You need to keep in mind that your erb code (the ruby code) is evaluated **on the server** where there is no window etc, and no client at all: the client stuff (ie your js.erb code) happens LATER. So this is like trying to reach into the future to read a variable. If you want the client to pass information to the server then it needs to be part of a request back to the server - in a cookie or in params. – Max Williams Nov 20 '15 at 09:43

2 Answers2

1

An alternative solution would be to get the URI on the rails side, fetch the project(s) and parse them to JSON - reparse them in js.erb and send the contents of the file to the client.

This way you do not have to execute JS on your server and you'll still have the project within the JS file you need.

This answer explains how to get the request URI for different rails versions.

For Rails 3.2 or Rails 4+

You should use request.original_url to get the current URL.

This method is documented at http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-original_url, but if you're curious, the implementation is:

def original_url
    base_url + original_fullpath
end

For Rails 3:

You can write "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

EDIT (20-11-2015)

Since you seem to be requiring a specific segment of the url, you could mimic the JS implementation with ruby easily by simply calling original_url.split('/')[2]

Community
  • 1
  • 1
SidOfc
  • 4,552
  • 3
  • 27
  • 50
0

You can easily do with https://github.com/sstephenson/execjs , as you can see

require "execjs"
ExecJS.eval "'red yellow blue'.split(' ')"

You can get the returning value easily.

Muaaz Rafi
  • 1,469
  • 2
  • 15
  • 23