Three or more level associations
Closed this issue · 5 comments
Actually I'm desperately trying to get a three-level association to work.
class Person < Spyke::Base
has_many :accounts
end
class Account < Spyke::Base
belongs_to :person
has_many :authorizations
end
class Authorization < Spyke::Base
belongs_to :account
end
Is there any way to achive such behavior without adding an additional .where
call at .authorizations
and pass in the parent idetifiers?
Hmmm do you have a usage example of what you're trying to do? 😄
Actually it would come in quite handy if we could do something like this:
p = Person.all.first # Just as an example
p.accounts.each do | account |
… # Do stuff with the account
account.authorizations.each do | authorization |
… # Do more stuff with an authorization
end
end
Im able to do so with has_many :authorizations, uri: '/people/:person_id/accounts/:account_id'
on the Account
model but then I have to call p.accounts.authorizations.where(person_id: p.id)
because person_id
gets lost on the last part of the association. Maybe I'm doing something wrong or I'm on the wrong track. The endpoint looks like this this /people/:person_id/accounts/:account_id/authorizations/:id
.
Aha, I see what you mean...Unfortunately I can't think of an easy to make that "automagically" work.
Assuming your JSON contains the required IDs, I suppose you could get close with something like:
class Account < Spyke::Base
def authorizations
Authorization.with("people/:person_id/accounts/:account_id/authorizations/:id").
where(person_id: person_id, account_id: id)
end
end
That of course won't work in all situations, but might get be enough for your purpose? 😓
@oliverzeyen closing this for now! Hoping you came up with a solution ☮️