Hi,
I would like to create an active record object from a string that I will
be passed. I could use eval but the documentation says that this can be
slow. Is there any other simple way to create an record object at run
time.
Thank,
HJS
Hi,
I would like to create an active record object from a string that I will
be passed. I could use eval but the documentation says that this can be
slow. Is there any other simple way to create an record object at run
time.
Thank,
HJS
What’s in the string ?
Fred
Frederick C. wrote:
What’s in the string ?
Sorry, I mean create an active record object from a string containing
the name of the object (which I won’t know till runtime).
HJS
Watch out! This can be a major security hole, if you’re not 100% sure
of whats in my_str.
H. joseph Solbrig wrote:
Hi,
I would like to create an active record object from a string that I will
be passed. I could use eval but the documentation says that this can be
slow. Is there any other simple way to create an record object at run
time.Thank,
HJS
Hi,
Generally the way to do it would be something like this:
myStr = “Post”
posts = myStr.constantize.find(:all)
Essentially what that is doing is taking the string “Post”, converting
it to the class with the name Post. So once you call constantize on that
string, you can call any of Post’s methods. In the end of this code, the
variable posts would contain a collection of all Post ActiveRecord
objects.
Marc Baumbach wrote:
H. joseph Solbrig wrote:
Hi,
I would like to create an active record object from a string
…myStr = “Post”
posts = myStr.constantize.find(:all)
…
How would you find out if the class “Post” existed?
(This is probably a newby but haven’t found it in my searches…)
HJS
Just out of curiosity, do you know why constantize uses module_eval
and not const_get?
If I was doing it without constantize, I would do it as:
begin
obj = Kernel.const_get(my_str).new
rescue
puts “no class named #{my_str}”
end
Michael
try
defined?(myStr.constantized) == “constant”
If it is defined, it will spit back “constant”, otherwise you could see
“method”. Normally, if you called defined? on an actual constant that
isnt there (i.e. defined?(Poster) ) you would get back nil, but since
you are trying to check the output of a method, instead of returning nil
it returns “method”
hope that helps
–jake
H. joseph Solbrig wrote:
Marc Baumbach wrote:
H. joseph Solbrig wrote:
Hi,
I would like to create an active record object from a string
…myStr = “Post”
posts = myStr.constantize.find(:all)…
How would you find out if the class “Post” existed?
(This is probably a newby but haven’t found it in my searches…)
HJS
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs