Extra Details
Let's make a small addition and improvement to the store.
user like count
Below the like button, can you display the number of users who liked the product?
Guideline: You already declared that each product has_many
likes, so can you use this relationship to display a number?
Add this code below your buttons:
<p><%= @product.likes.size %> users like this.</p>
.size
returns the number of items.
(You could also use .length
or .count
but .size
is more flexible.)
errors and bugs
What happens when someone who isn't logged in visits /my_page
? Try it out:
Rails provides a helpful error page so you can see what went wrong.
undefined method `liked_products' for nil:NilClass
"undefined method" means your code called a method on something that didn't have that method defined anywhere. In this case, it tried calling liked_products
on nil
, but nil
doesn't have such a method. Rails shows you where the code was called, so you can identify the issue quickly:
<%= render current_user.liked_products %>
current_user
was a devise method to return the signed-in user, and you could then call any of User's methods, such as liked_products
. However, if the visitor isn't signed-in, current_user
will return nil
and cause the above problem.
To fix this error, we'll want to prevent visitors who aren't signed in from visiting this page. Is there a Devise method that can help us with this?
Fortunately, Devise provides the method :authenticate_user!
and shows how to use it.
Add the following code to your UsersController:
before_action :authenticate_user!
Now try visiting the page again. This time, you'll be prompted to sign in. After signing in, you'll be redirected to /my_page
.