3

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 ?

potashin
  • 44,205
  • 11
  • 83
  • 107
Georgi Kovachev
  • 633
  • 1
  • 10
  • 25
  • Have you checked [Active Record Associations docs](http://guides.rubyonrails.org/association_basics.html#scopes-for-has-one)? For making it a dynamic condition you can use lambdas like illustrated in [this SO answer](http://stackoverflow.com/a/2462397/2116518). – Nic Nilov Jul 14 '16 at 18:09

2 Answers2

5

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'

menisy
  • 83
  • 1
  • 5
0

You can add a association like below in your driver model.

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

Here i am assuming that a boolean bit is present in your Haul model to check the current status.

Gurpreet Singh
  • 209
  • 1
  • 9