Rails one-to-one relationship

爷,独闯天下 提交于 2019-12-02 20:52:02

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
Robert

There are certainly a couple different ways of accomplishing this. I would suggest creating a composite key index on that table to ensure that the user_id is unique in the table. This will ensure that it will only be present once. In a migration, you could write something like this.

add_index(:cars, :worker_id, :unique => true)

The first argument is the table name (don't forget this is generally the pluralized version of the class name). The field name comes second. The unique true is what will prevent you from inserting an extra row.

Note: This is a database level constraint. If you hit this because validations didn't catch it, it will throw an error.

In addition to this solution, you will want to add a validation to the Car model itself.

validates_uniqueness_of :worker_id, message: "can not have more than one car"

You'll see this error come through with something like "Worker ID can not have more than one car". You will most likely want to customize the "Worker ID" section of this. Refer to this post for instructions on how to do that.

You certainly don't have to do the db constraint, but in case anyone else inserts into the DB, it's a good idea. Otherwise, you'll have "invalid" data as far as Rails is concerned.

Richard Brown

Change the definition of the relationship slightly:

class User < ActiveRecord::Base
  has_one :car

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

And you'll establish what you're looking for. See: http://guides.rubyonrails.org/association_basics.html#the-has-one-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!