Active Record and Ruby on Rails strange behaviour

41 Views Asked by At

Hi I have two models which are related to each other through a third model. The two main models are User and Club which have a relation through the Reservations table. The Reservation model has a column called active which is a boolean. The relationship between User and Club is a has_many to has_many ,through Reservation

When a user makes a reservation in a club, an entry is made in the reservation table and the field in the reservation active column is set to true. If the user makes another reservation at the same club, then the previous reservation should have the active column updated from true to false

Here is my code:

user = User.where(:email => params["user_email"]).first
club = Club.find(params["club_id"].to_i)

reservation = Reservation.new
reservation.club_id = club.id
reservation.user_id = user.id
reservation.active = true

user.reservations.where("club_id = ? AND active = ?", club.id, true).each do |res|
    puts res.id
    res.active = false
    res.save
end

reservation.save

Now the user.reservations.where("club_id = ? AND active = ?", club.id, true) query returns the correct entries. I update the value and save it again. However when I look in the database I still see active column has the value true.

What is even stranger is when I run the same command, which I used in my code, in the rails console, it returns the correct entries. When I modify the command a bit and try to find all the entries with column marked as false I also get the right entries. If I select an entry which should have active marked as false, and try this reservation.active == false this returns false, but when I run user.reservations.where("club_id = ? AND active = ?", club.id, true) the results does not contain the entry.

Can anyone explain why I am seeing such strange behaviour. Thanks in advance

* UPDATE *

Here is my schema

create_table "reservations", force: :cascade do |t|
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
    t.integer  "club_id"
    t.integer  "user_id"
    t.boolean  "active"
  end

create_table "clubs", force: :cascade do |t|
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.string   "name"
  end

create_table "users", force: :cascade do |t|
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string   "email"
  end
0

There are 0 best solutions below