Jay
Jay

Reputation: 6244

Eager Loading in a Rails 3 app

I am trying to reduce the number of database queries in my Rails 3 app.

User model:

has_many :agreements

Agreement model:

belongs_to :user

The agreements table has two user id fields... payer_id and payee_id. Is it possible to make something like the following work:

user_payer_agreements = current_user.agreements
user_payee_agreements = current_user.agreements

I could use user_id for one side of the transaction but I need to get both sides. Is it possible to specify payer_id or payee_id instead of user_id in the process of creating an association? If not, do i need use a join or a sql statement. Any help is appreciated.

Upvotes: 1

Views: 76

Answers (1)

Mischa
Mischa

Reputation: 43318

You can do this:

has_many :payer_agreements, :class_name => 'Agreement', :foreign_key => :payer_id
has_many :payee_agreements, :class_name => 'Agreement', :foreign_key => :payee_id

With this you can do:

current_user.payer_agreements
current_user.payee_agreements

Is this what you are looking for?

Upvotes: 2

Related Questions