【发布时间】:2015-08-04 16:53:26
【问题描述】:
我在 2 个 mongoid 模型之间有一对一的关联,并且我不断收到重复,即有多个具有相同 parent_id(即用户)的子记录(卡)。我已尝试验证如下所示的 belongs_to 关联的唯一性,但它不起作用。
class User
include Mongoid::Document
field :name, type: String
has_one :card
end
第二种模式:
class Card
include Mongoid::Document
field :name, type: String
belongs_to :user
validates :user, :uniqueness => {:scope => :user_has_child}
def user_has_child
q = Segment.where(drop_id: {'$ne' => nil})
s = q.map(&:drop_id)
errors.add(:drop_id, "this user already has a card") if s.include?(:drop_id)
end
end
【问题讨论】:
-
我不明白你为什么需要比
validates_uniqueness_of :user_id更复杂的东西? (或者我认为user也应该可以) -
谢谢你是正确的。我以前尝试过,但似乎没有用。但是当你建议它时,我再次尝试它并失败了然后我意识到我需要重新加载数据以查看它没有保存到数据库中,即使内存中的副本仍然显示错误的记录没有保存到分贝。
-
酷。我回答了更多细节,您可以投票和接受;-)
标签: ruby-on-rails ruby-on-rails-4 mongoid mongoid4