【问题标题】:Edit MongoMapper Document编辑 MongoMapper 文档
【发布时间】:2011-06-05 02:58:07
【问题描述】:

在 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,我一次只能编辑一个。

我错过了什么,还是什么?

【问题讨论】:

    标签: ruby mongodb mongomapper


    【解决方案1】:

    您编辑文档/对象的方式与编辑 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
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      相关资源
      最近更新 更多