How do I write an initializer so that it only runs when the database is configured correctly?

I have an initializer that wants to get a variable from a database. This initialization is only needed when running the application from rails server

or in production because it is only used in views.

config.default_country_id = Spree::Country.find_by(name: 'Netherlands').try(:id)

      

When run rake db:setup

on an empty database (or any rake task) it fails because the table in which the value is being retrieved does not exist ( db:setup

trying to create it).

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'revitalised_staging.spree_countries' doesn't exist:...

      

How would I write an initializer like this? Can I wrap it in some general condition that allows me to skip it if the database is not configured correctly? Should I instead only run it when I know what it needs (i.e., a whitelist of multiple commands or modes?).

+3


source to share


2 answers


You can ask ActiveRecord if the table exists and set the parameter only if it does. I think you can add some kind of fallback, but since the value is only used in views, I wouldn't bother.



if ActiveRecord::Base.connection.table_exists? Spree::Country.table_name
  config.default_country_id = Spree::Country.find_by(name: 'Netherlands').try(:id)
end

      

+1


source


config.default_country_id = Spree::Country.find_by(name: 'Netherlands').try(:id) if defined?(Spree::Country) 

      

should do the trick :-)



Link: https://www.ruby-forum.com/topic/171753

0


source







All Articles