I'm building an API, I have 2 models User and Coin.
The Coins table stores the default coins that can be added to the user's account.
I need to save the coins ids that the user decided to add in a column of the User model (my_coins), and be able to list only the coins saved by the user.
The problem is that I'm using sqlite3 and I can't save an array in a column
Routes.rb
get '/getCoins', to: "coins#index"
post '/coin/add', to: "users#add_coin"
users_controller.rb
class Api::V1::UsersController < ApplicationController
before_action :validate_jwt # Validates JWT, @current_user
before_action :user_coins_params
def add_coin
coin_acronym = user_coins_params[:id]
if Coin.find(coin_acronym).exists?
# @current_user CURRENT USER LOGGED IN ACTIVE RECORD
# ADD THE ID OF COIN TO MY_COINS COLUMN
if # push id of coin to my_coins column success
render json: { success: true, message: "Moeda cadastrada com sucesso!" }
else
render json: { success: false, errors: @current_user.errors }
end
else
render json: { success: false, message: "Moeda não encontrada" }
end
end
private
def user_coins_params
ActiveModelSerializers::Deserialization.jsonapi_parse!(params)
end
end
coins_controller.rb
class Api::V1::CoinsController < ApplicationController
before_action :validate_jwt # VALIDATES JWT, @current_user
before_action :set_coin, only: [:show, :update, :destroy]
# /coins GET USER COINS
def index
@coins = # GET USER COINS (@current_user.my_coins.each { |coinId| ... })
render json: @coins, include: [:mining_type]
end
end
has_and_belongs_to_manyassociation betweenusersandcoins. And in that case you will use acoins_usersjoin table instead of an array column on users.