编辑MongoMapper文档

时间:2011-06-05 02:58:08

标签: ruby mongodb mongomapper

在MongoMapper文档中没有任何地方可以找到实际编辑文档的任何方法。我也找不到其他地方的东西。我能找到的唯一方法是这种方法:

class User
  include MongoMapper::Document

  key :name, String
end

user = User.create( :name => "Hello" )
user.name = "Hello?"

puts user.name # => Hello?

有更简单的方法吗?我知道在DataMapper中,我可以一次编辑多个键(或DM的属性),但是对于MM,我一次只能做一个。

我错过了什么,或者是什么?

1 个答案:

答案 0 :(得分:4)

您编辑文档/对象的方式与编辑ActiveRecord对象的方式相同:为属性指定一些值,然后调用save

您的示例只有一个键,所以这里有一个多键:

class User
    include MongoMapper::Document
    key :name, String
    key :email, String
    key :birthday, Date
    timestamps! # The usual ActiveRecord style timestamps
end

然后:

user = User.create(
    :name     => 'Bob',
    :email    => 'bob@example.com',
    :birthday => Date.today
)
user.save

后来:

user.name     = 'J.R.'
user.email    = 'dobbs@example.com'
user.birthday = Date.parse('1954-06-02')
user.save

或者update_attributes

user.update_attributes(
    :name  => 'J.R. "Bob" Dobbs',
    :email => 'slack@example.com'
)
user.save

也许我不确定你在问什么。

相关问题