一对一关系 [英] Rails one-to-one relationship

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

问题描述

我有以下内容:

class User < ActiveRecord::Base
  has_one :car, :class_name => 'Car', :foreign_key => 'user_id'

class Car < ActiveRecord::Base
  belongs_to :worker, :class_name => 'User', :foreign_key => 'user_id'

这基本上是用户与汽车之间的一对一关系.

It is basically a one-to-one relationship between a user and a car.

我想要的是,用户只能拥有一辆汽车.这意味着如果他创建了分配给他的汽车,那么他将无法创建第二个汽车.

What I want is for the User to be able to have one and only one car. That implies the fact that if he creates a car assigned to him, he won't be able to create the second.

这怎么办?

推荐答案

为什么不只是在用户尝试添加汽车之前进行测试?

why don't you just test before the user tries to add a car?

if worker.car
 raise "sorry buddy, no car for you"
else
 car = Car.create(user_id: worker.id)
end

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

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