vigetlabs / sprig-reap

Sprig-Reap is a gem that allows you to output your application's data state to seed files.
MIT License
18 stars 18 forks source link

look up ActiveRecord::Base.descendants instead of .subclasses #27

Open simmerer opened 8 years ago

simmerer commented 8 years ago

Backstory

In Rails 5, all models inherit from ApplicationRecord, which inherits from ActiveRecord::Base ( https://github.com/rails/rails/pull/22567 ). For instance, my User model:

class User < ApplicationRecord
    # model stuff
end

sprig-reap looks up models via ActiveRecord::Base.subclasses, which only looks up direct subclasses of ActiveRecord::Base. As a result, rake db:seed:reap in Rails 5 fails silently with no records reaped:

D, [2016-07-15T11:48:44.342965 #93348] DEBUG -- : Reaping records from the database...
D, [2016-07-15T11:48:44.345559 #93348] DEBUG -- : Finished reaping!

Reaping from the Rails console shows the error:

$ rake db:seed:reap MODELS=User
rake aborted!
ArgumentError: Cannot create a seed file for User because it is not a subclass of ActiveRecord::Base.

Tasks: TOP => db:seed:reap
(See full trace by running task with --trace)

Change

Using the .descendants method, however, all levels of subclassing can be accessed, and I can successfully reap all of my models.

Rather than changing sprig-reap to look up direct subclasses of ApplicationRecord, I've modified it to call ActiveRecord::Base.descendants. This should preserve compatibility with pre-Rails-5 models that inherit directly from ActiveRecord:Base and/or don't inherit from ApplicationRecord.

h0tl33t commented 8 years ago

Thanks for the PR! I need to add some additional tests around STI to make sure the change from ActiveRecord::Base.subclasses to ActiveRecord::Base.descendants doesn't result in an extra seed file being generated for the base class. If it does, I'll have to handle that case.

Either way -- appreciate this! I'll try to get on the STI thing sometime over the next week.