0

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 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.

4

2 回答 2

5

你快到了,直接使用类对象,像这样:

my_models = [Category, Hierarchy]

my_models.each do |klass|
  a_region = klass.find_or_initialize_by_code(:code)
    ... 
    ...
  a_region.save!
end
于 2013-06-12T15:39:06.450 回答
2

你可以这样做,

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 将字符串转换为类

于 2013-06-12T15:38:45.340 回答