Accessing models from within the lib directory in a Rails 3 project

后端 未结 5 742
天涯浪人
天涯浪人 2021-01-03 06:04

I have a file in the lib directory that uses some constants defined in a model, like:

class User < ActiveRecord::Base
   MAX_EMAIL_ADDRESS_LENGTH = 255
en         


        
5条回答
  •  梦谈多话
    2021-01-03 06:33

    I know this is a old question but I've just faced the same problem and after some searches, I found a solution so I think it worth to share it.

    I wanted to use a model "Foo" in one required files located in my /lib directory. First, I did this and it didn't work :

    # in my rake file
    task :foo_task do
      require /some_path/lib/bar.rb
    end
    
    # in /lib/bar.rb
    puts "Foo = #{Foo.count} "
    
    # => uninitialized constant Foo
    

    After some searches, I found that to access models in my lib's files, I need to specify the environment in my task. So I just added this to my task declaration :

    task :foo_task => [:environment] do
    

    Now, when I call my task, it correctly puts the number of Foo :

    # => Foo = 6
    

提交回复
热议问题