likes_countattribute to the existing products API.
likes_countcolumn to the
spree_productstable, but in our case we also want to know which users liked which products, so that a product cannot be liked twice by the same user and we can personalize the user's recommendations based on the products they liked. We will also want to make sure that unauthenticated users cannot like a product, because we wouldn't be able to associate that like to a specific customer.
ProductLike, which we'll use to store the user-product relationship:
createaction that allows us to like a product.
find_productretrieves a product by its numeric ID or slug.
current_api_userretrieves the currently authenticated user (by default, all API requests require authentication).
invalid_resource!generates a 422 response that exposes all the error messages on an ActiveModel-compliant object.
ProductLikeinstance. The user ID is represented as an integer, while the product is transformed into a full JSON object by using Solidus'
resource :product_like) rather than a collection (
resource :product_likes). This is because a user may only have one like for a product. We are also limiting the routes for that resource to the
:createaction, since we are not going to implement the others.
Spree::Productmodel and expose it in our API. In order to do this, we first need to add the column to the
likes_countcolumn is automatically updated with the number of users who have liked the product. In order to do this, we can use ActiveRecord's excellent counter cache feature. Let's modify the
belongs_to :productassociation by enabling the option:
product.json.jbuilderview from Solidus and add the field there, but then we would need to remember to update our custom view every time the original view is changed.
ApiHelpersmodule. Let's see how we can do it and test it: