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?

Aaltan Ahmad
  • 141
  • 1
  • 6

1 Answers1

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?

Community
  • 1
  • 1
Kiran A B
  • 901
  • 1
  • 7
  • 13