Forum: Ruby on Rails ActiveRecord query in initializer file

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jej (Guest)
on 2008-11-25 18:06
(Received via mailing list)
Hi all,

I set up a constant in an initializer file (under /config/initializers/
myfile.rb) like this:

MYCONST = Model.find(:all).size

The problem is that rake fails to run some operations like db:migrate
or db:reset, due to the fact that my Model table doesn't exist at some
stages. Even with a "unless Model.nil?" it fails.

How can I test if the model exists to avoid error during rake? I don't
need this constant for rake tasks but only for normal execution of my
app.

Read you,
Jej
Jeff C. (Guest)
on 2008-11-25 18:43
(Received via mailing list)
On Nov 25, 10:05 am, Jej <removed_email_address@domain.invalid> wrote:
> Hi all,
>
> I set up a constant in an initializer file (under /config/initializers/
> myfile.rb) like this:
>
> MYCONST = Model.find(:all).size

Model.count is preferred here.  Model.find(:all).size loads everything
into memory first.

> The problem is that rake fails to run some operations like db:migrate
> or db:reset, due to the fact that my Model table doesn't exist at some
> stages. Even with a "unless Model.nil?" it fails.
>
> How can I test if the model exists to avoid error during rake? I don't
> need this constant for rake tasks but only for normal execution of my
> app.
>
> Read you,
> Jej

I think you want defined?(Model), i.e.:

MYCONST = Model.count if defined?(Model)

Jeff

purpleworkshops.com
Jej (Guest)
on 2008-11-25 18:52
(Received via mailing list)
> Model.count is preferred here.  Model.find(:all).size loads everything
> into memory first.

Thanks for this trick.

> MYCONST = Model.count if defined?(Model)

Yes, perfect!

Thanks Jeff.
This topic is locked and can not be replied to.