Iggy
Iggy

Reputation: 5251

Passing variables from application.html.erb to controller in Rails?

I have a variable inside application.html.erb's <script>:

...
<script>
  ...
  pos = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  };
  ...
</script>

Is there a way to pass it down to one of my controllers (posts_controller.rb)'s method (some_method)?

I need to get both latitude and longitude that is generated inside the script into posts_controller. How can I do this?

EDIT: (I didn't mention it, but some_method does not use get 'some_method', but post)

#routes
post 'some_method' => 'posts#scrape', as: :some_method

Upvotes: 1

Views: 310

Answers (1)

Eric Duminil
Eric Duminil

Reputation: 54223

GET request

You could use

window.open("/posts/some_method?longitude="+pos['lng']+"&latitude="+pos['lat'],"_self")

inside your <script>.

POST request

With jquery, you could use :

$.post("/posts/some_method?longitude="+pos['lng']+"&latitude="+pos['lat'])

For vanilla javascript, see this answer.

In some_method, longitude and latitude will be available in params[:longitude] and params[:latitude].

You can set instance variables (e.g. @lat and @lon) inside some_method, and those variables will be available in the corresponding view.

Upvotes: 1

Related Questions