Unlike Button


Collapse Content

Let's create an unlike button for users to unlike products. We'll start off in a similar manner as the like button, but then do things a little differently.

route and action

When a user unlikes a product, a like record is destroyed. Can you follow standard Rails practice to create a route and action for unliking a product?

The Code

Now let's fill in the controller code for destroying a like. This is simpler than creating a like, since we can just take in the id of the like and destroy it, we don't need to deal with any product. Can you fill in the destroy method so it destroys the like record with the given id?

Controller Code

setting up

Before we create the unlike button, we need to figure out how to display everything. Both buttons should only be shown to signed in users. The unlike button should only be shown to a user who likes a product, and the like button should only be shown to users who don't like a product. Can you setup these conditions on the product show page?

View Code

unlike button

Now that everything is setup, let's create the unlike button form. When dealing with an actual model object, Rails provides the form_for helper to make forms even simpler. First, can you write the ruby code to get the currenty_user's like item for the given @product?

Ruby Code

Now that we have the like, let's use the form_for helper to create the form:

<%# your previous line of code %>
<%= form_for(like, method: :delete  do %>
    <%= submit_tag %>
<% end %>

Notice that we specify the method as :delete so the form submits a delete http request, which will be routed to our delete action. This is all we need for the form to work, but let's again change the text displayed on the button:

 <%= submit_tag "Unlike" %>

We should now be able to like and unlike products!

cleanup

To make things neater, let's move the forms to partials. Create a partial _like for the like button and _unlike for the unlike button. Render the partials inside your product page.

Partials Code

Contact Us
Sign in or email us at [email protected]