How can I send a value from another field on a page via link_to with Rails?

Here is what I want to do:

<%= link_to "Approve", brand_user_brand_roles_path(@brand),
    :with => "forms[0]['user_brand_role_role_id'].value", :method => "POST", :remote => true %>

I know this is not working. I want to call the controller method remotely, including as a parameter the value that is selected in a field other than what is pressed.

How can I use Javascript to link to another field in link_to? Or is there another strategy that is better?

+1
source share
3 answers

Ok, unobtrusive javascript time, based on comments for my other answer.

I grabbed this from one of my projects, so you may have to adapt it to your needs, but it should give you an idea of ​​what to do. jQuery 1.3.2, FYI.

  $('form.link_id').livequery('submit', function(){
    $.ajax({
      url: $(this).attr('action'),
      data: $(this).serializeArray(),
      type: 'POST',
      error: function(xhr, status, error){
        alert("Save failed. Please check the form and try again.\n" + (error || status));
      },
      success: function(content){
        // do something with reply if you want.
      },
      dataType: 'html'
    });
    return false;
  });

Then the link is pretty simple:

<a href='/resource/new' id='link_id'>
+1
source

jQuery, - :

$('#id-of-field').val() # or value() depending on your js

, : with statement:

:with => "'role_id=' + $('#user_brand_role_role_id').value() +
 '&other_value=' + $('#id_of_other_thing').value()"

JS, , link_to.

+2

link_to_remote in earlier versions of the rails would solve your problem. But link_to_remote is no longer present from rails3, as they have moved away from obsessive javascript. However, you could use link_to_function , which can call a javascript function to help you get. Refer link_to syntax with rails3 (link_to_remote) and basic javascript that doesn't work in rails3 application? This discussion is for more details.

+1
source

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


All Articles