Rails Serializer Return Previous Data If Statement Exist

Viewed 42

I have some problems on rails api serializer. There is a if statement for update object, and when I update the object, it returns previous data. But If I remove the if statement then it returns updated version of object.

   if @store.schedule_relations.present?
    params[:schedule_params].each do |schedule_param|
       @store.btc_box_merchant_lku_schedule_relations.find_by(day: schedule_param[:day]).update_attributes!(is_open: schedule_param[:is_open], opening_time: schedule_param[:opening_time], closing_time: schedule_param[:closing_time])
    end
  end

Store Model looks like this:

has_many: :schedules

Schedule Model looks like this:

belongs_to: :store

If I remove if statement, it does work without to reload method. I can solve with reload, I'm wondering why it behaves like this. Any idea?

1 Answers

When calling a relation like @store.schedule_relations in Ruby on Rails then the result of that query is cached until the end of the current request. Therefore when you change the underlying data then those changes will not show up in subsequent calls of @store.schedule_relations.

To clear the cache and force a reload of the associated record with the updated data your need to call

@store.schedule_relations.reload

See ActiveRecord::Associations::CollectionProxy#reload.

Related