0

I am a part of a team that is creating a chess app in Rails 5. I have a controller named "chess_pieces.rb". In there I have the following code:

  def update
    @piece = ChessPiece.find(params[:id])
    @game = Game.find_by_id(@piece.game_id)
    @move = @piece.moves.all

    @piece.update_attributes(pieces_params)
    if @piece.valid?
     redirect_to game_path(@game)
    else
      render :edit, status: :unprocessable_entity
    end
    update_moves
  end

  def update_moves
    puts "The piece has been updated!"
    @piece = ChessPiece.find(params[:id])
    @piece.moves.update(count: 19991)
    @piece.save
    puts @piece.moves.count
  end

As you can see the update method, is updating a piece when it is moved, specifically the x_position and y_position on the chess board. Now, how do I make the method update_moves update the attributes of a table called moves which is associated with the chess_piece.rb model. I am calling this method in the update method after a piece“s location on the board is updated.

I want to update the count of how many moves the piece has made + some other stuff.

My routes are the following:

Rails.application.routes.draw do
  devise_for :users
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'games#home'
  resources :games do
    resources :pieces, only: [:show, :update]
    patch 'update_moves', on: :member
  end


end

1 Answers1

0

Is the relationis is (piece has_many moves) ?

If so, I don't think you can update all moves of a piece with @piece.moves.update(count: 19991) . You should update them individually with an iteration or a map.

Note: If you are trying to add a new move record to the piece then you should use @piece.moves.build(count: 19991)

If the relation is one to one then you should try replacing @piece.moves.update(count: 19991) with @piece.moves.count = 19991 ?

TamerB
  • 1,401
  • 1
  • 12
  • 27