her
her copied to clipboard
Association between a Her model and a regular ActiveRecord model
I building a Rails app which has several models, but which also has to interact with other virtual models, through various external APIs. Let's say I have the following two models:
class Client < ActiveRecord::Base
end
and
class Payment
include Her::Model
belongs_to :client
end
Now, as you can see, a Payment
is linked to a Client
, but it seems that Her expects Client
to be a Her model also.
How can I associate a regular ActiveRecord model with a Her model?
Hi @linkyndy hmm - tricky. I would probably use instance methods to approximate the relationship here - on Client you could have:
class Client < ActiveRecord::Base
def payments
Payment.where(client_id: self.id).to_a #without the to_a you'll get an unexecuted query
end
end
Could that work?
This is the approach I've followed, but would still like to see a better, "official" way to do it. I believe it would be useful for many!
Ideas about how it could work or - even better - a PR welcome @linkyndy :) I think the main issue is the fact that the associations, while sharing method names, are fundamentally different. Will give it some thought.
@edtjones The solution you proposed works, but has limitations. When you have a collection of clients and you also need to access the payments, how would you prevent the N+1 queries problem?
I wonder if there has been any development on this or if anyone has settled on good way to approach this problem?
Hi @heldersantosmoreira we haven't had the need to investigate this so I'm sorry - there are no better suggestions. But ideas are welcome.