0

I have a helper method that creates a link to follow an entity. This is based on this answer. Here's the code:

def link_to_follow(thing, extra_css_classes="")
  if current_user.following?(thing)
    link_to(
     "Unfollow",
     send("unfollow_#{thing.class.name.underscore.pluralize}_path", id: thing.id), 
     method: :post, 
     id: "unfollow_link_#{thing.id}",
     class: "btn btn-outline-primary btn-block #{extra_css_classes}",
     remote: true)
  else
    link_to(
      "Follow",
      send("follow_#{thing.class.name.underscore.pluralize}_path",id: thing.id), 
      method: :post, 
      id: "follow_link_#{thing.id}", 
      class: "btn btn-primary btn-block #{extra_css_classes}", 
      remote: true)
  end
end

This calls the follow/unfollow controller remotely, makes the user follow/unfollow the entity, and then replaces the existing button with javascript:

$("#follow_link_<%=instance.id%>").replaceWith("<%=j link_to_follow(instance)%>");

My problem is that when old button is being replaced with the new one, the extra_css_classes are not passed to the new link_to_follow and therefore it ends up looking differently.

Is there a way to get the css classes from the old button and pass them to the link_to_follow helper?

amoks
  • 123
  • 9
  • How do you choose which classes to pass when you call the button the first time ? And why not passing them in your new button ? – Maxence Feb 08 '21 at 00:34
  • To call the helper I would do something like: `<%= link_to_follow(instance, "btn-sm")%>`. – amoks Feb 08 '21 at 00:37
  • How do I make the follow/unfollow controller know what the classes of the old button are so they are passed through? – amoks Feb 08 '21 at 00:39
  • Is it not something that you know beforehand ? You need to pass that data to the controller action so you can populate it back to the new button ? If you need to "post" you can check this link : https://stackoverflow.com/questions/13414663/using-rails-link-to-for-links-that-post basically I would say make the button a form and pass a params that is `extra_css_class` so you can pick it back in controller. It seems a bit convoluted for just CSS though – Maxence Feb 08 '21 at 00:45
  • Also you are already doing something kinda similar with `id: thing.id` you can pass a parameter containing the css string in another param. (you are not using a form though but will work) – Maxence Feb 08 '21 at 00:54

0 Answers0