开发者

rails3 link_to :with attribute?

i am wondering if the :with attribute is removed from rails3 since i cannot find anything in 开发者_如何学JAVAthe rails3 api - http://rails3api.s3.amazonaws.com

anyone has a clue or give a hint on how to use the :with parameter to send data with a link_to

non-working example:

= link_to "Foo", {:action => "filter", :filter => "filter1",:with => "'test='+$('search').value"}, :remote => true, :class => "trash unselected", :id => "boo"

thanks!


I was struggling with this today and after a while I came up with little hack in rails.js. In handleRemote method I've changed this:

} else {
    method = element.attr('data-method');
    url = element.attr('href');
    data = null;
}

to this:

} else {
    method = element.attr('data-method');
    url = element.attr('href');
    data = eval(element.attr('data-with'));
}

Thank's to that now I can use link_to :remote like this:

<%= link_to "link", some_path, :remote => true, 'data-with' => "'address=' + $j('#office_address').val();" %>

NOTE: this is only valid if you are using jquery, but it shouldn't be difficult to apply this for prototype


This goes against the point of non-obstrusive javascript and this is why it has been removed. Try looking at the railscast about the subject here: http://railscasts.com/episodes/205-unobtrusive-javascript

You should try another way of doing this.


There is though a way to work around it.

Use this in the view as a guideline:

link_to "Foo", {:action => "filter", :filter => "filter1"}, {:remote => true, :class => "trash unselected", :id => "boo", 'data-with' => "'&test='+$('search').value"}

(moved :with to the second part and made it 'data-with')

and add this to the bottom:

<script type="text/javascript" charset="utf-8">
  $$('a[data-remote=true]').each(function(a){
    a.onclick = function(){a.setAttribute('href', a.getAttribute('href') + eval(a.getAttribute('data-with')))};
  });
</script>

of course you will need to have prototype loaded (is in the default javascripts of a rails app)


For something a better than this one-liner: http://gist.github.com/451508

Using the gist you don't need to start :with with & or ?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜