开发者

How can I cycle through a dynamic set of Active Record Models?

开发者 https://www.devze.com 2023-01-20 00:15 出处:网络
I have three Models (and growing): ContactEmail, ContactCall, ContactPostalcard I want to cycle through the three of them to go through a pretty lengthy loop.

I have three Models (and growing): ContactEmail, ContactCall, ContactPostalcard

I want to cycle through the three of them to go through a pretty lengthy loop.

A sample would would be the following:

import_event = ContactEmail.sugarcrm_is(false) #using searchlogic gem

The second loop wo开发者_如何学运维uld be:

import_event = ContactCall.sugarcrm_is(false)

I would I guess like a way to do something like:

event_array = ["ContactEmail", "ContactCall", "ContactPostalcard"]

event_array.each do |event|
  import_event = event_array.sugarcrm_is(false)
  .....

end

But not sure how to do that...thanks!


There are multiple ways to attack it, but the easiest is probably the following:

event_array = ["ContactEmail", "ContactCall", "ContactPostalcard"]
event_array.each do |event|
  import_event = event.constantize.sugarcrm_is(false)
  ...
end

constantize converts the string into a constant. Then you can make the class calls. It's a rails helper function.

You could also just have the array contain the classes instead of strings:

event_array = [ContactEmail, ContactCall, ContactPostalcard]
event_array.each do |event|
  import_event = event.send(:sugarcrm_is, false)
  ...
end

It's a little cleaner, but it all comes down to preference.

0

精彩评论

暂无评论...
验证码 换一张
取 消