I'm having some issues with my code. This is probably due to some design fault. I've tried several things. Here are two.
Issue: I have a 1 (lending) - N (contracts)
relation. I'd like to call lending.current_contract
which would return the last relevant contract.
Optimization is also an issue. I'd like to call :lending, :include => :contracts
without having to use separate queries for contracts which are already in the contracts array containing all contracts.
Bad solution 1:
has_one :current_contract, :class_name => "Contract"
This doesn't work because every time I create, update or destroy it has to update the parent lending as well. Doing this I get a callback mess. For example when creating a lending, it also creates the first contract. For some reason going back and forth using callbacks for both the lending as its contract doesn't work.
Bad solution 2:
def current_contract
return if contracts.relevant.empty?
@current_contract = contracts.relevant.last
end
Sends a copy and not the reference. So lending.current_contract.status = value
doesn't work.
Is there some design pattern which I should look at? And are there some examples? I've looked at some github projects but none of them had similar problems solved, therefore I think it is a design problem.