ruby 通过rails中的数据更新has_many的问题

c8ib6hqw  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(87)

我正在做一个项目,我的模型是:
user has_many setups,
setups通过instrumentsetups具有_many仪器,
instruments has_many setups通过instrumentsetups,
instrumentsetups belongs_to setups,
instrumentsetups belongs_to instruments,
现在我有它,你可以更新所有的参数在设置,但我试图使它,所以你也可以更新哪些文书是在设置在同一时间,但我有问题。我从setups_controller中的create方法中借用了一些代码来帮助我更新仪器,但我遇到了一个问题,无论我选择了多少个新仪器,它都会复制最后一个选择的仪器。以下是我在setups控制器中的所有代码:

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

这里也有一张照片,它是如何显示在我的前端只显示多个副本的同一文书,而不是所有的我选择的

toiithl6

toiithl61#

更新与创建不同,在更新操作中,您必须更新对象本身,而不是模型,因为您正在检索设置,并且设置通过instrumentsetups具有许多仪器,因此您可以像这样更新

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

相关问题