Search code examples
ruby-on-railsruby-on-rails-3models

get model attribute dynamically in rails 3


How can I get the attribute from the model object dynamically? I have the attribute of the User object as string:

u = User.find(1)

Can I do something like u.get("user_id")


Solution

  • You could try using the ActiveRecord model instance like a hash.

    u = User.find(1)
    name = u[:name]
    field = "first_name"
    first_name = u[field]