How to replace link_to_function for rails 4.1

I'm in the middle of building my first real Rails application, and I'm learning along the way. I have a situation where I need to create nested attributes in one form, and therefore they consider railscast episodes related to this (196 and 197). In the second episode, he uses the link_to_function method, which is apparently no longer available in rails 4.1.

I wonder how to replace it. I am trying to set link_to and have tried many of the suggested solutions for others that posted a similar question but to no avail.

This is how my view partially looks (although, I tried a lot of things ...)

<p class="offset1 fields"> <%= f.hidden_field :_destroy %> <%= link_to "remove", '#', onclick: 'remove_fields("this")' %> </p> 

And here is my .js.coffee file containing the remove_fields () function:

 remove_fields = (link) -> $(link).previous("input[type=hidden]").value = 1 $(link).up(".fields").hide 

This function should remove the field from the form, but instead simply appends '#' to the URL without calling the function.

What is the best way to reference javascript (coffeescript) function in assets from view?

+5
source share
1 answer

A good way to handle this:

a) Set the href attribute to "javascript: void (0);" b) Set the DOM id or CSS class attribute

 <%= link_to "remove", "javascript:void(0);", id="remove_link" %> 

c) Add a js listener for your element (check if this is the correct coffeescript syntax)

 $ -> $('#remove_link').click = ()-> $(link).previous("input[type=hidden]").value = 1 $(link).up(".fields").hide 

d) Always avoid using onclick: on html elements.

UPDATE:

e) The following is an alternative to what might work for your code (after your comment):

 $ -> $('#remove_link').click = ()-> $('.offset1.fields input').attr('value', 1); $('.offset1.fields').hide(); 
+4
source

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


All Articles