Liked Products Page
Now that the Like model, relationship and methods are set up, let's create a page for users to view all their liked products. Afterwards, we'll create a button for liking products.
Create my_page
Create a page called my_page that users can visit at /my_page.
Guideline: Create a my_page
controller action in UsersController and a my_page
file in views/users. Create the necessary route to point to it.
Create the controller action:
controllers/users_controller.rb
class UsersController < ApplicationController
def my_page
end
end
Create the file views/users/my_page.html.erb
and add some text to it, such as:
<h2>Liked Products</h2>
Add the following route to routes.rb
:
get 'my_page', to: 'users#my_page'
You should now be able to navigate to /my_page.
Filling in my_page
Manual Sample Data
If you haven't already done so, create a few likes in the command line so you can see how my_page displays them before you even create the like button. (Make sure to create the likes for the user account you're logged in on.)
Displaying Liked Products
Add code to your my_page file to display the products for the current user. You may find the Devise current_user
helper method to be useful. Can you display all the liked products with one line of code?
Since you already have a _product partial, it's very easy to display all the products in a collection:
views/users/my_page.html.erb
<h2>Liked Products</h2>
<%= render current_user.liked_products %>
(Compare this code with your code from the show category page.)
Account Info
Since you now have a personal page for the user, you can add some additional account info and links to the page. Here are 3 things to add:
- Move the Logout link from your navigation bar to my_page.
- Display the email of the logged-in user
- Add a link for a user to edit their account info. Open /rails/info/routes and find the named path that Devise provides for this purpose.
Here's the complete my_page:
views/users/my_page.html.erb
<h2>Liked Products</h2>
<%= render current_user.liked_products %>
<hr>
<h3>Account</h3>
<p>You are logged in as <b><%= current_user.email %></b>.</p>
<ul>
<li><%= link_to 'Edit profile', edit_user_registration_path %></li>
<li><%= link_to "Logout", destroy_user_session_path, method: :delete %></li>
</ul>
After removing the link to logout from the top of your site, can you add a link to my_page? It should only be displayed to logged-in users.
Here's the complete views/layouts/_header.html.erb
:
<header class="navbar">
<%= link_to "Home", root_path %>
<div class="u-pull-right">
<%= link_to "About", about_path %> |
<% if user_signed_in? %>
<strong><%= link_to "My Page", my_page_path %></strong>
<% else %>
<%= link_to "Sign up", new_user_registration_path %> |
<%= link_to "Login", new_user_session_path %>
<% end %>
</div>
</header>
my_page
should look something like this: