her icon indicating copy to clipboard operation
her copied to clipboard

Association between a Her model and a regular ActiveRecord model

Open linkyndy opened this issue 8 years ago • 6 comments

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?

linkyndy avatar Apr 26 '16 11:04 linkyndy

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?

edtjones avatar Sep 29 '16 19:09 edtjones

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!

linkyndy avatar Sep 29 '16 20:09 linkyndy

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 avatar Sep 29 '16 20:09 edtjones

@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?

mauro-ni avatar Jun 07 '18 14:06 mauro-ni

I wonder if there has been any development on this or if anyone has settled on good way to approach this problem?

helderasmoreira avatar Sep 02 '20 10:09 helderasmoreira

Hi @heldersantosmoreira we haven't had the need to investigate this so I'm sorry - there are no better suggestions. But ideas are welcome.

edtjones avatar Sep 07 '20 18:09 edtjones