首页 > 解决方案 > How to update a specific field in Mongodb knowing it's name?

问题描述

I have the following code

def update_field(db_entity, field_name)
  db_entity_value = db_entity.attributes[field_name]
  if db_entity_value == false
    db_entity.update(field_name: true) # db_entity.update(person_name: true) works!
  end
end

it takes two vars: db_entity and field_name(it's a string value like "age" or "weight"). I want to update the value of field_name. I can get its value by using db_entity.attributes[field_name] and then I want to set the value to true if it was false, but I don't know how to update it because field_name it's a variable which holds a field name that I want to update. Please, help.

标签: ruby-on-railsrubymongodbmongoid

解决方案


def update_field(db_entity, field_name)
  db_entity_value = db_entity.attributes[field_name]
  if db_entity_value == false
    db_entity.update(field_name => true)
  end
end

In Ruby when you construct hashes with the hashrocket (=>) syntax the keys can be variables.

You can also use update_attribute(name, value).


推荐阅读