Home > Back-end >  Accessing models and modules in a Rails 7 initializer
Accessing models and modules in a Rails 7 initializer

Time:09-29

This issue relates to a need to set a Rails config variable as the application boots, and the value of that variable needs to come from data in the database (which are then modified). So, I have an initializer with something like this:

require "#{Rails.root}/lib/modules/facet_altering.rb"
include FacetAltering

Rails.application.config.reject_subjects = FacetAltering.reject

The reject method is potentially slow and calls the Subject model (which includes some concerns).

If I try to require subject.rb, application_rb and the relevant concerns from app/models then I progress a bit further, but eventually get stuck on uninitialized constant Subject::MySpecialConcern.

There might be some better way to set the reject_subjects value; I'd prefer not to run FacetAltering.reject each time the value of reject_subjects is used, though this might be an easy 'fix' if no other solution arises (at the cost of slowing things down). Or, is there another way to access these classes as the application boots?

Edit: Following on from the comment below, this is in config/application.rb:

%W[#{Rails.root}/lib/modules #{Rails.root}/test/mailers/previews].each do |path|
      config.eager_load_paths << path
    end

CodePudding user response:

This post offered a useful clue:

Rails Model no longer available in initializer after upgrade to Rails 7.0

So, putting my code in config/application.rb as follows did the trick:

config.after_initialize do
    Rails.application.config.reject_subjects = FacetAltering.reject
end

Now to find the answer to RuntimeError: Foreign key violations found in your fixture data. Ensure you aren't referring to labels that don't exist on associations. and I might be able to complete this Rails 6 -> 7 upgrade!

  • Related