如何摆脱 Rails 3 应用程序中的这种冲突情况?
在 config/initializers/ 下,我有一个 ruby 文件,它将从数据库加载我的默认“car”实例的 ID。所以,在我的应用程序启动后,我的应用程序可以直接使用这个默认的汽车ID。
但是,我需要首先将这辆默认汽车插入数据库,因此,我需要rake(种子)任务或数据库<将默认汽车存储到数据库 Cars 表中。
冲突来了!如果我运行 rake 任务或迁移以将实例插入数据库,则初始化程序文件将始终在运行任何内容之前首先运行,这意味着“config”下的 ruby 文件/initializers/”将获取默认汽车的nil id,因为默认汽车尚未已存储在数据库中。
那么,如何消除这种冲突呢? (拥有该初始化程序文件的目的是仅加载一次默认汽车 ID)是否有其他方法仅加载默认汽车 ID 一次?
-------------编辑----------
初始化器下的代码:
default_car=Car.where({:name => DEFAULT_CAR_NAME})
def default_car_id
return {:default_car_id=>default_car.id}
end
Under config/initializers/, I have one ruby file which will load the id of my default "car" instance from database. So, that after my application started up, my application can directly use this default car id.
BUT, I need to firstly insert this default car into databasae, so, I need either a rake (seed) task or alternatively a database migration to store the default car to database Cars table.
Here comes the CONFLICT! If I run rake task or migration to insert instance to database, the initializer files will always be run FIRSTLY before anything run, which means the ruby file under "config/initializers/" will get nil id of default car, because the default car has NOT YET been stored in database.
So, how to get rid of this conflict? (The purpose of having that initializer file is to load default car id only ONCE) Is there any other way to load the default car id only once?
-------------Edit----------
code under initializers:
default_car=Car.where({:name => DEFAULT_CAR_NAME})
def default_car_id
return {:default_car_id=>default_car.id}
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不会那样做——这看起来很混乱。单个数据库查询并不是很昂贵,所以我会在您的汽车模型中执行类似的操作:
如果要更改的话,将 DEFAULT_CAR_NAME 放入 yaml 配置文件中可能是个好主意,否则我' d 只是硬编码它。
I wouldn't do it like that - it seems quite messy. A single database query isn't very expensive, so I'd do something like this in your Car model:
Would probably be a good idea to put the DEFAULT_CAR_NAME in a yaml config file if it's going to be changed at all, otherwise I'd just hardcode it.