0

Lately, I have been using the next initializer in a Rails 5 project:

initializers/initialize_configs.rb

$current_city = Config.first.city

But after a few changes, I had to rails db:migrate and rails db:seed and then, I got this error. Until that point, my application worked well.

Config is a one-row only table in which I save configs for each VPS, and $current_city is also a var the each VPS has.

The problem is that this error show up when I do rails db:seed, and so I cant load my initial configuration.

How could I fix the problem while still loading this initial dalta?

enter image description here

Juanse Cora
  • 755
  • 9
  • 19

1 Answers1

1

When you run rails db:seed then Rails is initialized, otherwise you were not able to use Rails models in that file. And that is the cause of your problem. Because in that initialization process Config.first.city must fail because there are is no data in the database yet.

It is unclear why you need to load the app's configuration from the database. And others already pointed out that this is questionable and feel like a code smell.

Nevertheless, currently you have two options:

  1. Do not use a Rails seed file to populate the database. Instead, use for example plain SQL. Or
  2. change the code in the initializer to be able to handle situations in which Config.first is blank. For example by using reasonable defaults.
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Your asnwer is partially correct, using $current_city = Config.try(:first).try(:city) all works fine. However, How could I get this global variable fulfilled from the ery beginning without initializers? – Juanse Cora Jul 14 '18 at 19:56
  • 1
    The question is why you need this global variable in the first place. And if it is a good idea to initialize it with a database record (MIght be surprising that the variable doesn't change when you change the record in the database). But I have no suggestions on how to fix that without knowing why you introduced a global variable like that and how your code looks. I assume that a config file or an environment variable would be a better choice. Btw the first `try` in your comment doesn't make sense, why would `Config` ever be `nil`? – spickermann Jul 15 '18 at 07:10