My relationship is as follows:
- Users have many Cartitems; Cartitems belong to Users,
- Cartitems have many Products; Products belong to Cartitems
- Therefore, Users have many Products through Cartitems and Cartitems have many Users through products.
I am trying to individually route to each users cartitems, something along the liens of: /users/:user_id/cartitems which will route to an array of cartitems belonging to that user, where I can then post, patch and delete cartitems for each user.
The problem is the path '/users/1/cartitems' returns the same cartitems as '/users/2/cartitems', and when I post to '/users/2/cartitems', the products get posted to '/users/1/cartitems'. I'm not quite sure if this is a problem in my routes or in my models/controller.
Here are my models for Users and Cartitems:
class User < ApplicationRecord
has_many :cartitems
has_many :products, through: :cartitems
end
class Cartitem < ApplicationRecord
belongs_to :user
belongs_to :product
end
And here are my serializers for good measure:
class UserSerializer < ActiveModel::Serializer
attributes :id, :username, :email
has_many :cartitems
end
class CartitemsSerializer < ActiveModel::Serializer
attributes :id, :user_id, :product_id, :quantity, :name, :price, :photo
end
And here is my Cartitems controller:
class Api::V1::CartitemsController < ApplicationController
before_action :find_cartitem, only: [:update, :destroy]
def index
@cartitems = Cartitem.all
render json: @cartitems
end
def create
@cartitem = Cartitem.new(cartitem_params)
if @cartitem.valid?
@cartitem.save
render json: @cartitem, status: :accepted
else
render json: {errors: @cartitem.errors.full_messages}, status: :unprocessible_entity
end
end
def update
@cartitem.update(cartitem_params)
if @cartitem.save
render json: @cartitem, status: :accepted
else
render json: {errors: @cartitem.errors.full_messages}, status: :unprocessible_entity
end
end
def destroy
@cartitem.destroy
render json: @cartitem, status: :accepted
end
end
private
def cartitem_params
params.require(:cartitem).permit(:user_id, :product_id, :quantity, :name, :price, :photo)
end
def find_cartitem
@cartitem = Cartitem.find(params[:id])
end
I want to be able to post to '/users/:user_id/cartitems' where each cartitems would be separate for each user ID. Any help would be greatly appreciated.