Methods and Products
Premium Content - Free Preview
User Methods
You saw how to set up code to create likes, now it's time to improve the code with some additional methods.
like
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
likes?
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
(Note that liked_products
is equivalent to self.liked_products
, it returns all the liked_products of the user.)
validation
Can you add validations to the Like model to make sure every like has a user_id
and product_id
?
validates :user_id, presence: true
validates :product_id, presence: true
dependent relationships
If you ever delete a user, their likes will still exist in the database.
End of Free Content Preview. Please Sign in or Sign up to buy premium content.