【问题标题】:Validating Associations with MongoMapper使用 MongoMapper 验证关联
【发布时间】:2011-11-30 21:36:55
【问题描述】:

型号:

class User
  include MongoMapper::Document
  many :properties
  validates_associated :properties
  ...
end

class Property
  include MongoMapper::Document
  belongs_to :user
  many :services
  validates_associated :services
  ...
end

class Service
  include MongoMapper::Document
  belongs_to :property
  ...
end

在控制器中:

@property.save #returns false and true as expected
current_user.save #returns always true why?

看来,它没有使用 current_user.save 方法验证属性模型。 为什么? :(

【问题讨论】:

  • 在我的简短测试中,validates_associated 仅适用于嵌入式关联。我正在调查,因为在代码中并不清楚为什么会这样。

标签: ruby-on-rails ruby ruby-on-rails-3 mongomapper


【解决方案1】:

在 MongoMapper 中,分配非嵌入式多关联会自动保存您关联的记录。但如果这些记录中的任何一条无效,它们就不会默默地保存到数据库中。下次您请求关联时,MongoMapper 会转到数据库,但什么也没找到。您分配的无效记录消失了。

user = User.new(:properties => [Property.new])
user.properties  # => []
user.valid?      # => true

您可以使用build 方法将对象添加到关联中而无需保存。

user = User.new
user.properties.build
user.properties  # => [#<Property _id: BSON::ObjectId('...0e'), user_id: BSON::ObjectId('...0c')>]
user.valid?      # => false

我认为关联保存是 MongoMapper 的弱点之一。然而,这不是一个容易的问题。有关挑战的讨论,请参阅 issue #233 on github

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多