[英]Need to run tasks on several rails models. Can I use an array do loop?
I have a rake task in which I operate on one model. 我有一个耙任务,我在一个模型上进行操作。 It updates and deletes stuff in the table.
它更新和删除表中的内容。 I have identical tables in other databases for which i created other models.
我在为其创建其他模型的其他数据库中拥有相同的表。 How can I run the same tasks on those other models without duplicating code and keeping things DRY?
如何在其他模型上运行相同的任务,而无需复制代码并使事物保持干燥?
for example here is my code: 例如,这是我的代码:
# Category is the model
new_region = Category.find_or_initialize_by_code(:code)
...
...
new_region.save!
I want to be able to do the same thing with another model called Hierarchy
But I don't want to duplicate code like this: 我希望能够使用另一个名为
Hierarchy
模型执行相同的操作,但是我不想重复这样的代码:
# Hierarchy is the model
new_cat_region = Hierarchy.find_or_initialize_by_code(:code)
...
...
new_cat_region_cat.save!
Is there a way I can create an array of models and loop through them like this? 有没有办法创建一个模型数组并像这样遍历它们?
my_models = ['Category', 'Hierarchy']
my_models.each do |model_name|
a_region = model_name.find_or_initialize_by_code(:code)
...
...
a_region.save!
How would the strings in the array be treated? 数组中的字符串将如何处理? Should this be okay?
这样可以吗 I feel uncomfortable with the type casting that may be happening behind the scenes in rails.
我对在Rails幕后进行的类型转换感到不舒服。
You're almost there, just use the class objects directly, like so: 您快到了,只需直接使用类对象,如下所示:
my_models = [Category, Hierarchy]
my_models.each do |klass|
a_region = klass.find_or_initialize_by_code(:code)
...
...
a_region.save!
end
You can do this as, 您可以这样做,
my_models = ['Category', 'Hierarchy']
my_models.each do |model_name|
a_region = model_name.constantize.find_or_initialize_by_code(:code)
...
...
a_region.save!
constantize will convert string into class constantize将字符串转换为类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.