简体   繁体   中英

Zero or one association in ActiveRecord

I am writing a Ruby on Rails application that has two models - User and Farm. A User is considered a farmer if their farmer field is set to true. However, there is no seperate class for farmers.

A User may have either one farm, or none at all. (I believe this is called a zero or one relationship). If I put:

has_one :farm

in the User model and

belongs_to :user

in the Farm model, this would create a one-to-one relationship between Users and Farms and mean that every User has a Farm. If I did the above, every User would have a Farm, and that would not make much sense since there are certain Users who cannot have a Farm.

In short, what I want is for a User to have a Farm only if their farmer boolean is set to true. Otherwise, the relationship shouldn't exist. Is their a way to do this using ActiveRecord the way it is meant to be used?

has_one doesn't mean that you must have one related entity(here farm). has_one is used for relation where we have 0 or 1 linked records.

You may find the similar discussion here.

Can has_one association be used when the model has one or zero instances of another model?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM