Zero or one association in ActiveRecord
Asked Answered
A

1

9

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?

Avie answered 13/11, 2012 at 21:43 Comment(9)
you could use validations ? guides.rubyonrails.org/…Projection
Validation is the way to go yeahCompline
So I should create the farm as a regular field and not using any of the association helpers? And then create a farm only if the validation "farmer == true" passes?Avie
Using an association is fine. It's not because you declare it that you have to fill it. It can be emptyCompline
@AnthonyAlberto will it impact the size/performance of the db if we have lots of Users with nil Farm associations?Avie
Nope, there wont be an empty entry on the Farms table for each user who isn't a farmer, so its ok to do it that way.Breastbone
Will be an empty farm entry for every user in the User table?Avie
Yeah but a null entry in SQL is like peanuts ... don't worry about it unless you have a lot of themCompline
possible duplicate of Can has_one association be used when the model has one or zero instances of another model?Chalmers
S
15

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?

Saurian answered 21/3, 2014 at 15:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.