如何验证 mongoDB 中关联对象的存在?
在我的应用程序中,我有这样的 Link 模型:
class Link
include Mongoid::Document
field :url, :type => String
validates_presence_of :url
belongs_to :link_bucket
end
和 LinkBucket 模型,它是从 FeedItem 模型继承的(在我的应用程序中 FeedItem 可以包含链接、消息、audio_track 等,这就是我使用继承的原因)。
class LinkBucket < FeedItem
has_many :links
end
那么在创建 LinkBucket 对象之前如何验证是否存在链接呢?
In my application I have Link model like this:
class Link
include Mongoid::Document
field :url, :type => String
validates_presence_of :url
belongs_to :link_bucket
end
and LinkBucket model, which is inherited from FeedItem model (in my app FeedItem could contain links, message, audio_track and so on, this is why I use inheritance).
class LinkBucket < FeedItem
has_many :links
end
So how can I verify if there is a link before I create LinkBucket object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非对象当时存在或正在创建,否则无法建立关联。但是,您可以在没有关联的
LinkBucket
的情况下创建一个Link
,然后再创建LinkBucket
并将它们关联起来。换句话说,仅当您确定拥有Link
并且需要创建一个LinkBucket
时,才创建一个LinkBucket
。这有帮助吗?You can't make the association unless the objects exist or are being created at the time. But you can create a
Link
without having an associatedLinkBucket
, and then later create theLinkBucket
and associate them. In other words, only create aLinkBucket
when you are sure you have aLink
and you need to create one. Does that help?