I am working on a project where my models are:
user has_many setups,
setups has_many instruments through instrumentsetups,
instruments has_many setups through instrumentsetups,
instrumentsetups belongs_to setups,
instrumentsetups belongs_to instruments,
right now I have it where you can update all of the params in the setup but I am trying to make it so you can also update which instruments are in the setup at the same time but I am having issues. I am borrowing some code from my create method in the setups_controller to help me update the instruments but I am having an issue where no matter how many new instruments I select it just makes a bunch of copies of the last instrument selected. Here is all of my code in my setups controller:
class SetupsController < ApplicationController
skip_before_action :authorize
def index
render json: Setup.all, status: :ok
end
def show
setup = Setup.find(params[:id])
render json: setup
end
def create
setup = current_user.setups.create!(setup_params)
if setup.valid?
params[:instrument_ids].each do |instrument_id|
InstrumentSetup.create(setup_id: setup.id, instrument_id: instrument_id)
end
render json: setup
else
render json: { errors: setup.errors.full_messages }, status: :unprocessable_entity
end
end
def update
setup = Setup.find(params[:id])
if setup && setup.user_id == current_user.id
params[:instrument_ids].each do |instrument_id|
InstrumentSetup.update(instrument_id: instrument_id)
end
setup.update!(setup_params)
render json: setup, status: :created
else
render json: "Invalid Credentials", status: :unauthorized
end
end
def destroy
setup = Setup.find(params[:id])
if setup && setup.user_id == current_user.id
setup.destroy
head :no_content
else
render json: "Invalid Credentials", status: :unauthorized
end
end
private
def current_user
User.find_by(id: session[:user_id])
end
def setup_params
params.permit(:name, :description, :photo, :genre, :instrument_ids)
end
def authorize
return render json: {error: "Not Authorized"}, status: :unauthorized unless session.include? :user_id
end
end
here’s also a photo of how its show up on my front end with only showing multiple copies of the same instrument instead of all of the ones I selected
>Solution :
updating is not like creating, in your update action you have o update the object itself and not the model, since you are retrieving the setup and setup has many instruments through instrumentsetups, you can update like this
def update
setup = Setup.find(params[:id])
instruments = Instrument.find params[:instrument_ids]
if setup && setup.user_id == current_user.id
setup.update(instruments: instruments)
setup.update!(setup_params)
render json: setup, status: :created
else
render json: "Invalid Credentials", status: :unauthorized
end
end
