I have created a bookmark action which kind of works however when I click "bookmark" or "unbookmark" it takes me to the show page which is not what I want, I would just like the icon I have clicked to change when I click on "bookmark" and "unbookmark" and stay on the same page (which is the index page). I have looked at other similar questions but they do not make sense to me, I saw that I may have to use something called AJAX however I am new to Ruby and not sure how to use this..

Here is my code, I think the issue is something to do with my link_to but I am not sure.

Thanks

index.html.erb file:

<div id="bookmark">
              <% saved_hairstyle = SavedHairstyle.find_by(user: current_user, hairstyle: hairstyle.id) %>
              <% if saved_hairstyle %>
                <%= link_to saved_hairstyle_path(saved_hairstyle), method: :delete, remote: true do %>
                <!--bookmarked-->
                  <i class="fas fa-bookmark"></i>
                <% end %>
              <% else %>
                <%= link_to hairstyle_saved_hairstyles_path(hairstyle), method: :post, remote: true do %>
                <!--un bookmarked-->
                  <i class="far fa-bookmark"></i>
                <% end %>
              <% end %>
            </div>

saved_hairstyles controller:

class SavedHairstylesController < ApplicationController
include Pundit
  after_action :verify_authorized, except: [:create, :destroy]

  def create    
    @hairstyle = Hairstyle.find(params[:hairstyle_id])   
    @saved_hairstyle = SavedHairstyle.new(user: current_user, hairstyle: @hairstyle)   
    if @saved_hairstyle.save
      respond_to do |format|         
        format.html { redirect_to hairstyle_path(@saved_hairstyle.hairstyle) }
        format.js  # <-- will render`app/views/saved_hairstyles/create.js.erb`
      end
    else
      respond_to do |format|
        format.html { render 'hairstyles' }
        format.js  
      end
    end
  end

  def destroy

    @saved_hairstyle = SavedHairstyle.find(params[:id])

    @saved_hairstyle.destroy
    @hairstyle = @saved_hairstyle.hairstyle
    respond_to do |format|
      format.html { redirect_to hairstyle_path(@saved_hairstyle.hairstyle)}
      format.js
    end
  end
end

create.js.erb file which executes when someone bookmarks a hairstyle:

plusCircle = document.getElementById("bookmark");
plusCircle.innerHTML = `<%= link_to  hairstyle_saved_hairstyles_path(hairstyle), method: :delete do %>
                    <i class="fas fa-plus-circle"></i>
                 <% end %>`

1 Answers

0
Amit Patel On

There are many issues with implementation. It woudn't be feasible to explain the solution.

I have created a PR https://github.com/Angela-Inniss/hair-do/pull/35 which would help you to understand.

Feel free to add PR comments if you want to understand the changes. Also you can reach out to me on https://twitter.com/amit_savani in case you still face issue with bookmarking