【问题标题】:Rails4 validate uniqueness of multiple columnsRails4 验证多列的唯一性
【发布时间】:2014-08-25 10:41:34
【问题描述】:

我有一个模型友谊,其中 :friend_id 也是外键 :user_id

友谊 编号 |用户 ID |朋友ID 我知道验证这两个字段的唯一性是这样的

validates :user_id, :uniqueness => {:scope => :friend_id}

但是有没有办法验证

user_id = 1, friend_id = 3
user_id = 3, friend_id = 1 

这样只存储user_id = 1,friend_id = 3?

【问题讨论】:

  • 为什么你不想拒绝第二种情况?这不是用户 20 添加用户 10 的场景吗?
  • 你使用的是哪个数据库??
  • 我还建议您将模型重命名为Friendship,因为您不创建和管理Friend,而是用户之间的友谊。
  • 在你的情况下 1 你的意思是数据不应该重复??有重复
  • 我会避免禁用第二种情况。老实说,这就是您应该如何创建友谊模型 - 始终为每个友谊建立两个连接,这样您就可以轻松加载它们(例如加入、包含)

标签: ruby-on-rails


【解决方案1】:

加入模特

看起来您正在使用带有 Rails 的 join model - 如 cmets 中所述,您需要将其更改为 friendship(而不是 friend)。

Rails 有两种类型的 join 机制 - has_many :throughhas_and_belongs_to_many - 都允许您关联 many-to-many 记录,如下所示:

#app/models/user.rb
Class User < ActiveRecord::Base
   has_many :friendships
   has_many :friends, through: :friendships
end

#app/models/friendship.rb
Class Friendship < ActiveRecord::Base
   belongs_to :friend, class: "User", foreign_key: "friend_id"
   belongs_to :user
end

#friendships
id | user_id | friend_id | created_at | updated_at

我建议您使用friendship 模型(与无模型的HABTM 设置相反),因为HMT 允许您添加额外的数据,例如created_atupdated_at、@987654337 @等)


自我参照

我也会使用self-referential 模型。这将允许您保留一个模型(用于User),然后调用@user.friends 没有问题。

我上面的关联定义是否正确是另外一回事;这就是您想要设置它们的方式。

--

验证

在验证您的关联方面,我相信您将能够使用indexes in your DB。这通常用于HABTM 表 -

#Migration

# Adding the index can massively speed up join tables. Don't use the
# unique if you allow duplicates.
add_index(:friendships, [:user_id, :friend_id], :unique => true)

这将适用于您的原始案例,但不适用于第二个案例

【讨论】:

    猜你喜欢
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2021-09-11
    • 1970-01-01
    • 2015-09-20
    • 2014-08-08
    相关资源
    最近更新 更多