Lucas d. Prim
Lucas d. Prim

Reputation: 787

Creating third level associations where second level belongs_to third on Rails ActiveRecord

I have the following model, Purchase, on my Rails app:

class Purchase < ActiveRecord::Base
  [...]
  belongs_to :payment, :validate => true
  belongs_to :day, :foreign_key => :day_day, :primary_key => :day, 
    :counter_cache => true
  [...]
end

And I have the Day model:

class Day < ActiveRecord::Base
  [...]
  has_many :purchases, :foreign_key => :day_day, :primary_key => :day
  [...]
end

I'd like to create an association between the day and the payments occurred during that day through the Purchase model. Is it possible?

Thanks a lot!

Upvotes: 0

Views: 376

Answers (1)

Adam Tanner
Adam Tanner

Reputation: 927

It might help if you can give a little more detail on why your relationships are set up the way they are.

My first question is what does a Day object consist of? Could it be replaced by having a "purchased_on" attribute on the Purchase model?
If so, this can be done pretty easily through a scope on Purchase.

Second, the way you have it now a single Payment has many Purchases. Is this really what you mean, or do you actually want a Purchase that has many Payments?

Let me know, and I'll see if we can get something worked out for you.

Upvotes: 1

Related Questions