Methods and Products
Premium Content - Free Preview
You saw how to set up code to create likes, now it's time to improve the code with some additional methods.
To make things simpler, create a method in User for liking products.
Here's one way you could create the method in User:
def like(product) Like.create(user_id: self.id, product_id:product.id) end
Rails also lets you mention the model directly instead of the ID, so you can shorten the code:
def like(product) Like.create(user: self, product: product) end
Add another method to user that checks if a user likes a specific product. To do this, check if the user's liked_products includes a given product.
(To find a method that check if an item exists in a collection, see Ruby Arrays or look at Ruby's enumerable docs.)
Get the user's liked products and check if they
include? the given product:
class User < ActiveRecord::Base #... def likes?(product) liked_products.include?(product) end end
liked_products is equivalent to
self.liked_products, it returns all the liked_products of the user.)
Can you add validations to the Like model to make sure every like has a
validates :user_id, presence: true validates :product_id, presence: true
If you ever delete a user, their likes will still exist in the database.