Find object based on string value

Hi all,

I have this method which, ideally, I would like to work in such a way as
I pass in three string values, the first is the name of the object I am
trying to instantiate, the second a string value corresponding to an
attribute for that object and finally the value that the attribute gets
updated with.

The second half of this I have working, but instantiating an object from
a string value is not working.

I have done several searches and have come up with a solution that runs
the correct query but doesn’t seem to create an actual object. Here is
what I have:

params => {:model => “user”, :attr => “name”, “user” => { “name” =>
“John”}}

def save_update
@obj = Object.const_get(:"#{params[:model]}").find(:first,
:conditions =>
[“upper(#{params[:attr]}) = ?”,
params[:"#{params[:model]}"][:"#{params[:attr]}"]])

if !@obj.blank?

end
end

When I get to the line checking to make sure the object is not blank
results in failure.

I guess my question is is this even possible and does anybody have any
suggestion on how to make this work? Thanks,

-S

Even when I try something like:

@obj = “#{params[:model]}”.constantize
@this = @obj.find(:first, :conditions => [“upper(#{params[:attr]}) = ?”,
params[:"#{params[:model].downcase}"][:"#{params[:attr]}"]])

I still have a null object.

On 23 April 2012 21:13, Shandy N. [email protected] wrote:

Even when I try something like:

@obj = “#{params[:model]}”.constantize
@this = @obj.find(:first, :conditions => [“upper(#{params[:attr]}) = ?”,
params[:“#{params[:model].downcase}”][:“#{params[:attr]}”]])

I still have a null object.

Why complicate things with the conditions when you are trying to get
the basic find going? What if you just do @obj.find :first
Look in development.log to see what query is being run.

Colin

My original code actually did work, I was having issues with another bit
of the code which was confusing the whole matter. Thanks for the
responses. Hopefully this helps someone, thanks,

-S

I would go with

@obj = “klass_name”.camelize.constantize

and then make use to use
@obj.responds_to? :attribute

to test for existence before you start finding and assigning