HABTM-唯一性约束 [英] HABTM - uniqueness constraint

查看:103
本文介绍了HABTM-唯一性约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有HABTM关系的模型-用户和角色.

I have two models with a HABTM relationship - User and Role.

  • 用户-has_and_belongs_to_many:roles
  • 角色-归属用户:user

我想在联接(users_roles表)中添加一个唯一性约束,该约束说user_id和role_id必须是唯一的.在Rails中,外观如下:

I want to add a uniqueness constraint in the join (users_roles table) that says the user_id and role_id must be unique. In Rails, would look like:

validates_uniqueness_of :user, :scope => [:role]

当然,在Rails中,我们通常没有模型来表示HABTM关联中的联接关系.

Of course, in Rails, we don't usually have a model to represent the join relationship in a HABTM association.

所以我的问题是添加约束的最佳位置在哪里?

So my question is where is the best place to add the constraint?

推荐答案

您可以添加唯一性来联接表

You can add uniqueness to join table

add_index :users_roles, [ :user_id, :role_id ], :unique => true, :name => 'by_user_and_role'

请参见您的数据库将引发一个异常,您必须处理该异常.
在这种情况下,我不知道准备使用Rails验证,但是您可以添加自己的验证,如下所示:

Your database will raise an exception then, which you have to handle.
I don't know any ready to use rails validation for this case, but you can add your own validation like this:

class User < ActiveRecord::Base
has_and_belongs_to_many :roles, :before_add => :validates_role

我只是默默地放弃数据库调用并报告成功.

I would just silently drop the database call and report success.

def validates_role(role)
  raise ActiveRecord::Rollback if self.roles.include? role
end

ActiveRecord :: Rollback是在内部捕获的,但不会重新捕获.

ActiveRecord::Rollback is internally captured but not reraised.

修改

请勿在我要添加自定义验证的部分使用.可以,但是还有更好的选择.

Don't use the part where I'm adding custom validation. It kinda works but there is better alternatives.

在关联中使用:uniq选项,如@Spyros在另一个答案中建议的那样:

Use :uniq option on association as @Spyros suggested in another answer:

class Parts < ActiveRecord::Base
  has_and_belongs_to_many :assemblies, :uniq => true, :read_only => true
end  

(此代码段来自Rails Guides v.3).请阅读 Rails Guides v 3.2.13 look对于4.4.2.19:uniq

(this code snippet is from Rails Guides v.3). Read up on Rails Guides v 3.2.13 look for 4.4.2.19 :uniq

Rails Guide v.4特别警告不要因为可能的比赛条件而使用include?检查唯一性.

Rails Guide v.4 specifically warns against using include? for checking for uniqueness because of possible race conditions.

有关添加索引到联接表的部分保持不变.

The part about adding an index to join table stays.

这篇关于HABTM-唯一性约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆