Passing a JavaScript variable to a ruby-on-rails controller

How to pass a variable (id) from a JavaScript listener:

Gmaps.map.callback = function() { ... ... google.maps.event.addListener(marker, 'click', function() { var id = this.currentMarker; alert(id); }); } } 

To instance variable (@foo) in ruby-on-rails controller

 def create @foo = ??? ... end 

to correctly create a relationship in a view (form):

 <%= form_for user.relationships.build(:followed_id => @foo.id) do |f| %> <div><%= f.hidden_field :followed_id %></div> <div class="actions"><%= f.submit "Follow" %></div> <% end %> 

Thanks!

+6
source share
1 answer

If I understand correctly, a good way to do this is to use AJAX to send an identifier to your action and use the action to render your form.

This would look something like this in your javascript:

 jQuery.ajax({ data: 'id=' + id, dataType: 'script', type: 'post', url: "/controller/action" }); 

You will need a route:

 post 'controller/action/:id' => 'controller#action' 

Then in your action, you can capture this identifier and make your form look something like this:

 def action @user = User.relationships.build(:followed_id => params[:id]) render :viewname, :layout => false end 

Then you can simply create a form for @user in partial or other

 <%= form_for @user do |f| %> 

You will need to fill in the details there, but it should be pretty close.

+4
source

Source: https://habr.com/ru/post/912791/


All Articles