16

Lets say I wish to make a page that can query the desired object with type(string) and id(int).

/query?type=people&id=1

would fetch me

Person.find(1)

whereas

/query?type=cities&id=123

would fetch me

City.find(123)

However, I have problems as to how to translate strings into the desired model class.

The only way I can think of is

case params[:type]
 when 'people'
  @object = Person.find(params[:id])
 when 'cities'
  @object = City.find(params[:id])
end

However, this method will be quite problematic if I have more types of models.

Is there a better way?

Thank you in advance,

2
  • 3
    If you try to do this automatically you may end up in a situation where an attacker can send "/query?type=TOP_SECRET_TABLE&id=1" and get information he shouldn't be allowed to access. Beware of what you wish for.
    – Sebi
    Feb 27, 2012 at 9:44
  • It is actually meant for the ajax for tagging objects. So my next step would be like @object.tags << tag. But wanted to keep the question simple so asked this way. Thanks anyways!
    – rickypai
    Feb 27, 2012 at 9:56

1 Answer 1

51

Try:

klass = params[:type]
klass.singularize.classify.constantize.find(params[:id])

Edit:

@object = params[:type].singularize.classify.constantize.find(params[:id])
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.