title: Create a dynamic subclass in Rails that works with STI
body: <p>I want to combine the two following things:</p>
  <h2>My STI structure:</h2>
  <p>Assume a Rails model <code>User</code>. There are only two types of users, namely <code>Admin</code> and <code>Customer</code>. The STI column is <code>type</code>, the table is called <code>users</code> but in practice, we will never have and <code>User</code> objects around, just <code>Admins</code> and <code>Customers</code>.</p>
  <ul>
  <li><code>User</code> (used for storing all data and implementing common functionality, but never instanciated)
  <ul>
  <li><code>Admin</code></li>
  <li><code>Customer &lt; User</code></li>
  </ul>
  </li>
  </ul>
  <h2>Dynamically extend models:</h2>
  <p>In some cases, it is handy to dynamically extend a model class, to temporarely have an object with more capabilities to carry out a specific action. Assume my <code>create</code> controller action checks for an additional field &quot;Send welcome mail&quot; (which is provided by the <code>new</code> form). The attribute is virtual, thus we can use it in the form as if it was a normal column. This can be realized with:</p>
  <pre class="lang-rb prettyprint-override"><code>extended_user_class = Class.new(User)
  extended_user_class.send(:include, MyAwesomeMixins)
  extended_user_class.class_eval do
    my_virtual_attribute :send_welcome_mail, default: true
  end
  
  model = extended_user_class.new
  # send model to the view and it &quot;just works&quot;
  </code></pre>
  <h2>Combining both</h2>
  <p>Unfortunately combining both of these techniques does not work in the way described above, because Rails STI appears to be broken by anonymous classes:</p>
  <pre><code>[1] pry(main)&gt; User.where(id: 1).to_sql
  =&gt; &quot;SELECT `users`.* FROM `users` WHERE `users`.`id` = 1&quot;
  [2] pry(main)&gt; Class.new(User).where(id: 1).to_sql
  =&gt; &quot;SELECT `users`.* FROM `users` WHERE `users`.`type` IS NULL AND `users`.`id` = 1&quot;
  </code></pre>
  <p>EDIT: To reproduce the above, must be in production env.</p>
  <p>The second statement is wrong because it filters by type. The first statement is the intended behavior.</p>
  <p>So, apearently anonymous classes are bad for STI. Redefining the constant <code>User</code> as described in <a href="https://dev.to/factorial/a-trick-with-ruby-anonymous-classes-11pp" rel="nofollow noreferrer">https://dev.to/factorial/a-trick-with-ruby-anonymous-classes-11pp</a> is likely to break the application - I want the extended class to only be used when called explicitely (<code>extended_user_class</code>) - <code>User</code> has to be unaffected.</p>
  <p>Can this be achieved in Ruby 3 / Rails 6?</p>