Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 936
Aaltan Ahmad Avatar asked Nov 13 '12 21:11

Aaltan Ahmad


People also ask

How would you choose between Belongs_to and Has_one?

They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.

What is Association in Ruby on Rails?

Association in Rails defines the relationship between models. It is also the connection between two Active Record models. To figure out the relationship between models, we have to determine the types of relationship.

What are Active Record methods?

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.


1 Answers

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?

like image 158
Kiran A B Avatar answered Sep 20 '22 07:09

Kiran A B