[英]how do I execute ruby code with access to the Database before rails application begins?
I will like to know how can I execute some ruby code just before the rails application begins. 我想知道在Rails应用程序开始之前如何执行一些ruby代码。 I need to have access to database and be able to set some variables for the views to access.
我需要访问数据库并能够设置一些变量以供视图访问。
Thanks. 谢谢。
I think, a better approach is to not go with database, but create a configuration file, say, app_config.yml in your application_root/config folder, and then load it using the following line in the environment.rb file. 我认为,更好的方法是不使用数据库,而是在application_root / config文件夹中创建一个配置文件,例如app_config.yml ,然后使用environment.rb文件中的以下行加载它。
APP_SETTINGS = YAML.load_file("#{Rails.root.to_s}/config/app_config.yml")
Your app_config.yml file looks like this 您的app_config.yml文件如下所示
appname: something.com
appsettings: something...
appvar: something...
You can access these config variables from anywhere in your application as: 您可以通过以下方式从应用程序中的任何位置访问这些配置变量:
APP_SETTINGS['appname']
and so on. 等等。
This yml file is loaded at the time the rails server is started. 在启动Rails服务器时将加载此yml文件。 Hence, if you make any changes to this file, your server should be restarted.
因此,如果对此文件进行任何更改,则应重新启动服务器。
If you want to set up something that the views can use right away, try sticking the code in db/seeds.rb
. 如果要设置视图可以立即使用的内容,请尝试将代码粘贴在
db/seeds.rb
。 That's where you should put any creation of objects that you might need, like reference data (eg populate a Countries table or set up some user Roles). 在此处应放置任何可能需要的对象的创建,例如参考数据(例如,填充“国家/地区”表或设置一些用户角色)。
It is automatically run when the DB is reset, or through rake db:reset
. 重置数据库时或通过
rake db:reset
自动运行它。
Use activerecord alone to set some constants. 单独使用activerecord设置一些常量。
http://weblog.jamisbuck.org/2005/10/3/easy-activerecord-scripts http://weblog.jamisbuck.org/2005/10/3/easy-activerecord-scripts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.