I am trying to apply AJAX on a toggle "Like" button. This setup updates the button status without refreshing the entire page, but the former <%= pluralize(@company.get_likes.size, "people liked it") %>
is not removed ("0" people liked it, is added to the new "1" people liked it")
How can remove the previous "@company.get_likes.size" people liked it
sentence?
How can I improve the code?
controller:
def toggle_favorite(company)
if user_signed_in?
if current_user.liked? company
link_to raw("<i class='fa fa-star'></i>"), unlike_company_path(company), remote: true, method: :put
else
link_to raw("<i class='far fa-star'></i>"), like_company_path(company), remote: true, method: :put
end
else
link_to 'sign in to like', new_user_session_path
end
end
route:
resources :companies do
member do
put "like" => "companies#like"
put "unlike", to: "companies#unlike"
end
end
view:
<div class="text-center">
<div id="<%= dom_id(company) %>">
<%= pluralize(company.get_likes.size, "people liked it")) %>
<%= toggle_favorite(company) %>
</div>
</div>
like.js.erb
let starIcon = document.querySelector("#company_<%= @company.id %>").querySelector('.fa-star')
starIcon.parentElement.outerHTML = "<%= pluralize(@company.get_likes.size, "people liked it") %> <%= escape_javascript(toggle_favorite(@company)) %>"
unlike.js.erb
let farstarIcon = document.querySelector("#company_<%= @company.id %>").querySelector('.fa-star')
farstarIcon.parentElement.outerHTML = " <%= pluralize(@company.get_likes.size, t('views.company.bookmark.count_bookmark')) %> <%= escape_javascript(toggle_favorite(@company)) %>"