Home Rails, polymorphic association. Destroy with "touch: true", useless steps
Reply: 1

Rails, polymorphic association. Destroy with "touch: true", useless steps

John Sam
John Sam Published in 2018-02-05 10:16:55Z

I'm on Rails 5.

I have a polymorphic association like this:


class EnjoyLevel < ApplicationRecord
  belongs_to :enjoyable, polymorphic: true, touch: true, optional: true


class Mother < ApplicationRecord
  has_one :enjoy_level, as: :enjoyable, dependent: :destroy

  accepts_nested_attributes_for :enjoy_level

If I destroy one mother (which have touch: true option) it still:

  • destroy the enjoy_level one before;
  • set Mother update_at to now();
  • and finally destroy this Mother record one.

The first and second steps are useless, right?

Where am I wrong?

AKovtunov Reply to 2018-02-05 10:41:31Z

From http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

:touch - If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on an attribute.

So when you are destroying mother, you are calling the dependent: destroy dependencies at first, that are your enjoy_level objects and because they have touch: true you are touching the mother object back (because it also updates it on destroy). So maybe 2nd query is useless in the current scenario, but they work as planned.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296317 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO