Home Rails STI sibling callbacks propagating
Reply: 1

Rails STI sibling callbacks propagating

Daniel Olivares
1#
Daniel Olivares Published in 2018-02-13 22:14:24Z

I'm facing an issue with STI (single table inheritance), where a callback that should only run on one of a child model's instances, actually runs on its sibling's instances as well, even though it shouldn't.

class Parent < ApplicationRecord; end

class FirstChild < Parent
  after_initialize :set_default_attr

  private
  def set_default_attr
    self.attr = "something"
  end
end

class SecondChild < Parent; end

second = SecondChild.new
assert_nil second.attr # Fails because it is set to "something"

I expect the #set_default_attr callback to run only on FirstChild instances, not on SecondChild ones. I think the current behaviour is counter-intuitive. Am I missing something?

Ruby version: 2.5.0, Rails version: 5.1.4


Update 1: It seems like also validations propagate

Update 2: A possible workaround would be to add something like this:

class FirstChild < Parent
  after_initialize :set_default_attr, if: :type_is_first?
  validate :attr, presence: true, if: :type_is_first?

  private
  def set_default_attr
    self.attr = "something"
  end

  def type_is_first?
    type == "FirstChild"
  end
end

however this feels super dirty to me.

Daniel Olivares
2#
Daniel Olivares Reply to 2018-02-13 23:08:14Z

My bad, I was inheriting from a wrong class...

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO