A. Singla A. Singla - 4 months ago 18
Ruby Question

Setting a model parameter whenever it is updated ruby on rails

new to rails here. I have an RoR app, which has a model called pieces. The pieces have an integer parameter called status. Whenever a piece is created or updated, I want the piece.status to be set to 2 if the devise current_user.id method is not equal to 1. This works for my create method, but when I put a similar line into my update method, nothing happens. What should I do?

Here is my controller

class PiecesController < ApplicationController
before_action :set_piece, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
respond_to :html

def index
@pieces = Piece.all
respond_with(@pieces)
end

def show
respond_with(@piece)
end

def new
@piece = current_user.pieces.build
respond_with(@piece)
end

def edit
end

def create
@piece = current_user.pieces.build(piece_params)
@piece.status = 2 if current_user.id != 1
flash[:notice] = 'Piece was successfully created.' if @piece.save
respond_with(@piece)
end

def update
flash[:notice] = 'Piece was successfully updated.' if @piece.update(piece_params)
respond_with(@piece)
end

def destroy
flash[:notice] = 'Piece was successfully deleted.' if @piece.destroy
respond_with(@piece)
end

private
def set_piece
@piece = Piece.find(params[:id])
end

def piece_params
params.require(:piece).permit(:title, :image, :genre, :size, :price, :description, :status)
end
end


Thanks guys!

Answer
class PiecesController < ApplicationController
  def update
    @piece.attributes = piece_params
    @piece.status = 2 if current_user.id != 1
    if @piece.save
      flash[:notice] = 'Piece was successfully updated.'
      respond_with(@piece)
    end
  end
end