4

i have some code that uses a string to determine dynamically what model class to use and for what field to find_by() on. however, i'm having a hard time with how to use these variables to get the model instance. specifically, i have

class Item
  include MongoMapper::Document
  key :my_variable, String

in my code i have

m = "Item"
f = "my_variable"

and i want to be able to

i = m.find_by_my_variable( f )
result = i[f]

any help is appreciated!

yee379
  • 6,498
  • 10
  • 56
  • 101

2 Answers2

6

Since you're in Rails (judging by the category tag) you can use:

m = m.constantize

to make the string a constant, and then would something like this work for your query?

m.where("#{f} = ?", some_value)

(EDIT) or use send as ismaelga suggested, if you don't want an ActiveRecord::Relation array object

Michael
  • 204
  • 1
  • 4
  • 1
    Your answer is as valid as mine. It has just a different sintax. And actually it's a lil better. I would change a little instead of `where("#{f} = ?", some_value)` could be `where(f.to_sym => some_value)` – Ismael Abreu Aug 07 '12 at 02:34
0

You could do eval(m.capitalize).send("find_by_#{variable_name}", variable_content)

Capitalize it's only to be sure it gets a capital letter.

Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75