Home > Software engineering >  How can i update an object properly?
How can i update an object properly?

Time:10-14

how can i update a object properly? my attempt is not working i am getting an error:"#<ArgumentError: wrong number of arguments (given 1, expected 2)>",

this is my endpoint:

def update
    @car = Car.find(params[:id])
    @car.update_attribute(car_params)
    render json: @car
  end

and the params are like this:

def car_params
      params.require(:post).permit(:title, :description)
    end

this is my query in postman

put->http://localhost:3000/cars?id=9

{"title":"new title", "description":"descriptions000"}

CodePudding user response:

Here you are trying to use update_attribute instead update_attribute.

For update_attribute

# Syntax 
update_attribute(name, value)

# example 
update_attribute(title, 'Ferrari')

For update_attributes

# Syntax 
update_attributes(attributes)

# example 
update_attribute({title => "Ferrari", :description => "This is my Car"})

Please change your endpoint as below

def update
  @car = Car.find(params[:id])
  @car.update_attributes(car_params)
  render json: @car
end

Please refer to update_attributes.

I hope this will help you.

CodePudding user response:

I suggest update! in cases like this.

def update
  @car = Car.find(params[:id])
  @car.update!(car_params) # <-
  render json: @car
end

update! is nice because it will raise an error when validations fail. If you use update (no bang) or update_attributes, you might silently fail to update anything, which may lead to confusing behavior.

  • Related