Lokesh Waran
Lokesh Waran

Reputation: 113

Store model name in an array rails

My requirement is something like this (but this doesn't work)

array=["Menu","Article","Comment"]
array.each do |x|
   x.find 1     # the x is of class String
   p x.id
end

each elements of the array is an model name in my application. The 'x' obtained inside the looping is of class string but i want it to be of a model.

I want to do certain same task on each of the models, doing something like this can reduce some 60 lines of code in my program. can anybody help..

Upvotes: 0

Views: 385

Answers (3)

IngoAlbers
IngoAlbers

Reputation: 5802

You can do it like this:

array=["Menu","Article","Comment"]
array.each do |x|
    a = (Object.const_get x).find 1
    p a.id
end

Upvotes: 1

dimakura
dimakura

Reputation: 7655

In ActiveSupport (part of Rails) there is a method constantize available on Strings which might help you:

array=["Menu","Article","Comment"]
array.each do |x|
  instance = x.constantize.find 1
  p instance.id
end

Upvotes: 1

John Gibbons
John Gibbons

Reputation: 322

You can use constantize like so:

array=["Menu","Article","Comment"]
array.each do |x|
  klass = x.constantize
  klass.find 1
  p klass.id
end 

http://apidock.com/rails/String/constantize

Upvotes: 2

Related Questions