Like Model
Premium Content - Free Preview
Let's add the ability for users to like products. This way, users can keep track of products they may be interested in buying later.
Tracking liked products
To set this up, we need to keep track of all the products a user likes. How can we store this information in the database?
First Attempt
To keep track of all the products in a category, we just added a category_id
to products. In this case, we could we add a user_id
to products which will be used to record the user that likes a given product.
You should be able to see why that won't work. Each product only belonged to one category, so we could add a category_id to products to track this relationship. But each product may be liked by many users, so one user_id
won't be able to track all the liking users. (We also cannot just add one product_id
to users, since a user can like many products.)
Solution
We need a way to track all the likes between products and users. Each user can like many products and each product can be liked by many users. This is called a many-to-many relationship. Instead of adding a single column to one model, we should create a new model to represent this relationship between users and products.
Let's create a new model called Like to keep track of all the likes. What custom columns should we put in likes? We just need two: product_id
and user_id
. Each like
item will store the id of the liking user and the id the liked product.
To get all the products liked by a user #1, the computer will get all the Likes where user_id
is 1, and then it can use the accompanying product_id's to get all the liked products.
In the above diagram, User #1 liked 3 products, with ID's 1,3, and 4.
Creating an Indexed Like Model
Go ahead and generate the model Like.
Enter the following in your terminal:
rails generate model Like user_id:integer product_id:integer
This will output:
invoke active_record create db/migrate/20150326201616_create_likes.rb create app/models/like.rb
After entering the above code, Rails will create a new Like model and migration file. Usually, we would run rake db:migrate
now to create the Likes database table, but let's first make some changes to the migration file.
Indexing
How does the computer get all the likes for a specific user_id? By default, the computer simply goes through all the likes from beginning to end and pulls out the ones with the specified user_id. This is fine for a small site, but can get slow when there are millions of likes. To speed things up, you should add an index
to columns that get looked up a lot. An index takes up some space, but it lets the database look up items much more quickly. You can tell Rails to create a database index for you by using the add_index method in the migration file.
End of Free Content Preview. Please Sign in or Sign up to buy premium content.