Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has_one conditions

I defined has_one relationship in drivers table

has_one :current_haul 

It is associated with hauls table.
And hauls table and drivers table, both of them has organization_id.

I would like to apply the conditions like this

select * 
from drivers 
join hauls on drivers.organization_id=hauls.organization_id
 and drivers.current_haul_id= hauls.id  

I can I put this conditions in has_one modifier ?

like image 348
Georgi Kovachev Avatar asked Nov 30 '25 04:11

Georgi Kovachev


1 Answers

This is how you can do it, simply add a boolean column on the Haul table. Maybe you will need a unique index to make sure you do not have multiple currents at any given moment.

has_one :current_haul, -> { where(current: true) }, class_name: 'Haul'

like image 57
menisy Avatar answered Dec 02 '25 19:12

menisy