使用 MongoMapper 验证关联

发布于 2024-12-19 01:17:01 字数 538 浏览 1 评论 0原文

模型:

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 方法验证属性模型。 为什么? :(

Models:

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

In controller:

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

It seems, that it doesnt validate the Property model with current_user.save method.
Why? :(

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟花肆意 2024-12-26 01:17:01

在 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 的弱点之一。然而,这并不是一个容易的问题。请参阅 github 上的问题 #233 了解有关挑战的讨论。

In MongoMapper, assigning a non-embedded many association automatically saves the records you're associating. But if any of those records are invalid, they silently aren't saved to the database. The next time you ask for the association MongoMapper goes to the database and finds nothing. The invalid records you assigned disappear.

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

You can use the build method to add objects to the association without saving.

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

I consider association saving to be one of MongoMapper's weak point. However, it's not an easy problem. See issue #233 on github for a discussion of the challenges.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文