ruby-on-rails - 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.
解决方案
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)
.
推荐阅读
- python - 多处理:如何 mp.map 将元素存储在列表中的函数?
- javascript - 如何将 user_id 传递给 Modal 弹出窗口并在 JSP 中显示相应的用户?
- php - 如何使用mysqli和php根据另一列连接和求和两个表中的列(仅使用查询)
- python - 如何提取嵌套在dict列表中的值列表?
- python - 如何在熊猫的给定两个日期之间查找是否需要工作日
- python - 创建具有给定行数和重复值的数据框
- firebase - 离子如何在注销/登录时显示/隐藏内容
- javascript - '$x' 未定义,同时在 IE11 控制台中验证 Webdriver 的 Xpath
- php - 尽管格式正确,MySQL 字段 DATETIME 仍会截断
- c# - 长文字和照片一排,缩小图片