Reputation: 3154
I went to through various similar questions like this and this, but that did not solve it for me.
My controller code.
# GET `/reservations/new`
def new
@user_id = current_user.id
if current_user.has_reserved
format.html { redirect_to reservations_url, notice: 'Only one reservation per customer is allowed' }
end
@car_id = params[:car_id]
@c = Car.where(:id => @car_id).first
puts "Hello"
puts @c.id
puts @c.update_attributes({:status => 'reserved'})
puts @c.status
@reservation = Reservation.new
end
This is my console, when I visit the page.
Hello
4
(0.1ms) begin transaction
(0.1ms) commit transaction
true
reserved
Now when I check the database in rails console
Car.where(:status => 'reserved')
This gives me no values. (Even Car.all
shows all car's status as 'available' which is the default)
Output of above :
irb(main):009:0> Car.where(:status => 'reserved')
Car Load (0.3ms) SELECT "cars".* FROM "cars" WHERE "cars"."status" = ? LIMIT ? [["status", "reserved"], ["LIMIT", 11]]
=> #<ActiveRecord::Relation []>
As I gathered from other questions, update_attributes
saves the record also. And it's returning true. Then why is it not reflecting in database?
Edit : Adding Model File Code
Car.rb
class Car < ApplicationRecord
validates_inclusion_of :status, :in => ['available','reserved','checked_out'], :default => 'available'
validates_inclusion_of :style, :in => ['coupe','sedan','suv'], :default => 'sedan'
validates_length_of :licence_plate, :is => 7, :unique => true
attr_accessor :status
end
Reservation.rb
class Reservation < ApplicationRecord
belongs_to :user
belongs_to :car
attr_accessor :can_checkout, :can_return, :can_reserve, :checked_out, :returned
end
Code from where reservation/new
is called,'views/cars/index.html.erb'.
<td><%= link_to "Reserve", controller: "reservations", action: "new", car_id: car.id%></td>
Upvotes: 0
Views: 596
Reputation: 48
The submit form action of reservation's 'new' view would call the 'create' method of the reservation controller to which you can pass your car_id as a parameter. Then in the submit method you can get the associated car by @car = Car.find(params[:car_id]) and try updating the car status
Upvotes: 1
Reputation: 3005
Does the car have a status field in the database?
If so, why do you use attr_accessor :status? in the model. It is not necessary if the field exists.
Remove the attr_accessor and add the field in the database if it is not present.
Upvotes: 2