开发者

How can I submit a value from another field on the 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", :开发者_如何学Goremote => true %>

I know that this doesn't work. I want to call a controller method remotely, including as a parameter a value that is selected in a field other than what is clicked.

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


If you're using prototype or jQuery, something like so will access the value in a field:

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

So, add that into your :with statement:

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

You can play around in the JS console to get the right output, then put it into your link_to statement.


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

I grabbed this from one of my projects, so you may need to tailor 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 basic:

<a href='/resource/new' id='link_id'>


link_to_remote in the earlier versions of rails would have solved your problem. But from rails3 link_to_remote is no longer present as they moved away from obtrusive javascript. You could however use a link_to_function which can call a javascript function which will do the get for you. Refer link_to syntax with rails3 (link_to_remote) and basic javascript not working in a rails3 app? this discussion for more details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜