Zero or one association in ActiveRecord

I am writing a Ruby on Rails application in which there are two models - User and Farm. A user is considered a farmer if the farmer field is set to true. However, there is no separate class for farmers.

A user can have either one farm or nothing at all. (I believe this is called zero or one link). If I put:

has_one :farm 

in the user model and

 belongs_to :user 

in the Farm model, this will create a one-to-one relationship between users and farms and means that each user has a farm. If I did this, each user would have a Farm, and that would not make much sense, as there are certain Users who cannot have a Farm.

In short, I want the user to have a farm only if his farmer boolean is set to true. Otherwise, the relationship should not exist. This is their way of doing this with ActiveRecord, how is it intended to be used?

+4
source share
1 answer

has_one does not mean that you should have one related object (here is the farm). has_one is used for a relationship where we have 0 or 1 related records.

Here you can find a similar discussion.

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

+7
source

Source: https://habr.com/ru/post/1445872/


All Articles