views:

34

answers:

1

Hello all, 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!

+1  A: 

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.

Adam Tanner
Hey Adam! Thanks a lot for your help! A Day model is just a model i use to avoid making requests to 5+ tables to get the data of a single day (money coming in, products going out, raw material flow). It simply is ran every end of the day and collect the data from the purchases and stuff. The payment has_one purchase because the customer can create more than one payment (if he goes to the credit card page, then comes back, then goes again to the bank debit page) and i didn't want to end with multiple payments referencing the same purchase..
Lucas d. Prim
I actually stopped searching for an answer to this problem as i found some workarounds simply stopping being lazy and started making multiple requests when needed to other models. The Day model is created only once a day and i can bear with the computing cost it has when it runs! Thanks a lot for your help!
Lucas d. Prim