Reputation: 1128
I am a beginner in all this and I am trying to build a very basic controller.
This is my write/create method:
It checks if an id is included in the params. If there is an ID, it does a put request to update an existing car. Otherwise, it just creates a new Car.
def write
if params[ :id ]
@car = Car.where( id: params[ :id ] ).first
params[ :car ].each do | key, value |
attribute = { "#{ key }": value }
@car.update_attributes( attribute )
end
else
@car = Car.new(
model: params[ :model ],
num_wheels: params[ :num_wheels ],
color: params[ :color ],
realm_uuid: params[ :realm_uuid ]
)
end
@car.save!
render json: @car
end
This is my routes.rb file:
Rails.application.routes.draw do
scope '/api' do
get '/' => 'cars#query'
post '/' => 'cars#write'
scope '/:id' do
get '/' => 'cars#read'
put '/' => 'cars#write'
delete '/' => 'cars#delete'
end
end
end
And finally my car.rb:
class Car < ApplicationRecord
attr_accessor :model, :num_wheels, :color, :realm_uuid
end
All the routes work correctly, I can create, read, update, and delete. The thing is that when I read, all the values are nil/null. When I make a post in Postman, the render json: @car
returns a correct car with all the values but when I make a get request, it says all the values are nil/null.
I also see an error: ArgumentError (Wrong number of arguments (given 1, expected 4)
This probably has something to do with it...
Upvotes: 1
Views: 1024
Reputation: 18454
attr_accessor
on a model makes an reader/writer method for instance variable with corresponding name.
In your case it overrides getter/setters for model attributes and thus you write to variable instead of attribute. So remove attr_accessor
and model should save correctly.
If you do not have these fields in db - then you should make a migration to add them.
Upvotes: 3