验证多态关联模型中的作用域唯一性 [英] Validate scoped uniqueness in polymorphic association models
问题描述
是的,所以我有一个多态关联,允许收藏不同的对象类型.所以一个人可以喜欢一个产品,一个人,或者其他什么.我想要做的是防止有人使用验证收藏夹模型中的唯一性来复制收藏夹.
Right, so I have a polymorphic association that allows for different object types to be favorited. So a person can favorite a product, or a person, or whatever. What I want to do is guard against someone duplicating a favorite using validates uniqueness in the Favorite model.
class Favorite < ActiveRecord::Base
belongs_to :favoritable, :polymorphic => true
belongs_to :user
attr_accessible :user
validates_presence_of :user
validates :user_id, :uniqueness => { :scope => [:favoritable_type, :favoritable_id] }
end
验证似乎有效,但无论出于何种原因,当尝试复制条目时,仍会使用 user_id 创建一个新的收藏夹行.
The validation seems to be working but for whatever reason a new Favorite row is still created with the user_id when an attempt is made to duplicate the entry.
有没有办法停止这个初始保存?
Is there a way to stop this initial save?
Rails 似乎正在创建 DB 条目,然后使用 favouritable_id 和 favouritable_type 更新它,如下所示:
It seems that Rails is creating the DB entry and then updating it with the favoritable_id and favoritable_type as follows:
SQL (28.3ms) INSERT INTO "favorites" ("created_at", "favoritable_id", "favoritable_type", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["created_at", Tue, 14 Aug 2012 10:26:31 UTC +00:00], ["favoritable_id", nil], ["favoritable_type", nil], ["updated_at", Tue, 14 Aug 2012 10:26:31 UTC +00:00], ["user_id", 23]]
(7.8ms) COMMIT
(0.1ms) BEGIN
Favorite Exists (0.3ms) SELECT 1 AS one FROM "favorites" WHERE ("favorites"."user_id" = 23 AND "favorites"."id" != 123 AND "favorites"."favoritable_type" = 'Style' AND "favorites"."favoritable_id" = 29) LIMIT 1
(0.2ms) UPDATE "favorites" SET "favoritable_id" = 29, "favoritable_type" = 'Style', "updated_at" = '2012-08-14 10:26:31.943937' WHERE "favorites"."id" = 123
(6.7ms) COMMIT
(0.1ms) BEGIN
推荐答案
如果你仔细观察,你会发现唯一性验证很好用 :)
If you closely observe you can find that uniqueness validation just work fine :)
validates :user_id, :uniqueness => { :scope => [:favoritable_type, :favoritable_id] }
查看您添加的数据图像.在图像内部,您可以发现第二条记录没有 favouritable
而第一条记录是不同的,因此 2 条记录是 uniq 并且它不是 uniqueness
的问题,而是您的逻辑差距.
Look at the data image you added. inside image you can find out that second record is not having favouritable
whereas first have which is different hence 2 records are uniq and its not issue with uniqueness
but its your logical gap.
如果您确实想避免第二次进入,请将 favouritable
保留为必填字段
If you strictly wanted to avoid second entry then keep favouritable
as mandatory field
validates :favoritable_type, :favoritable_id, :presence => true
这篇关于验证多态关联模型中的作用域唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!