0
votes
  1. This is my in my pages.home.html.erb

      <div id="favorites-div">
        <% if current_user.voted_for? item %>
          <%= link_to '<i class="fas fa-minus-square plus_and_minus_button"></i>'.html_safe, item_unlike_path(item.id)%> 
        <% else %>    
          <%= link_to '<i class="fas fa-plus-square plus_and_minus_button"></i>'.html_safe, item_like_path(item.id)%>
        <% end %>
      </div>
    
  2. I am using a 'acts_as_votable' gem

  3. I have nested these 2 get's in my items: routes: get 'like', to: 'items#like' get 'unlike', to: 'items#unlike'

  4. In my items controller I have defined 2 methods: def like item = Item.find(params['item_id']) item.liked_by current_user redirect_back fallback_location: root_path end

    def unlike item = Item.find(params['item_id']) item.unliked_by current_user redirect_back fallback_location: root_path end

4.1 These two methods are available in the whole ItemsController class and they are not inside inside any of the CRUD methods.

My questions would be: 1. What JS function would you recommend? Do I remove and then add the ID in the div? 2.Do I just load the div again? (.load) 3. Do i need to create a new file in my Rails app to implement this method?

Your kind help is very appreciated!

1
I would recommend placing the html you wish to re-render inside a separate partial file. This blog explains the general concept coderwall.com/p/kqb3xq/rails-4-how-to-partials-ajax-dead-easyOzgar

1 Answers

0
votes

The traditional way to do this in Rails has been to render a new HTML fragment on the server, and send it across to the browser wrapped in JavaScript that knows how to update the DOM with the new HTML when the browser received and evaluates it.

To do this you need to set up a few things:

  • The fragment you want to render dynamically should be moved to a partial, so you can render it independently of any view
  • You need an ID on the containing element, so you can easily figure out where to insert the re-rendered HTML
  • You need a .js view that can render the partial, along with the JavaScript required to update the DOM.
  • You should use remote links

Your HTML views should look something like this:

# pages.home.html.erb

<div id="favorites-div">
  <%= render 'votes' %>
</div>

# votes.html.erb

<% if current_user.voted_for? item %>
  <%= link_to '<i class="fas fa-minus-square plus_and_minus_button"></i>'.html_safe, item_unlike_path(item), data: { remote: true }%> 
<% else %>    
  <%= link_to '<i class="fas fa-plus-square plus_and_minus_button"></i>'.html_safe, item_like_path(item), data: { remote: true } %>
<% end %>

Your new JavaScript view should render the partial, and replace the existing HTML with the new HTML, using the j helper to escape JavaScript characters in the returned string:

# unlike.js.erb

$('#favorites-div').html('<%=j render 'votes' %>')