开发者

Rails 3 Associations for Traffic Data without Foreign Key

开发者 https://www.devze.com 2023-02-15 17:14 出处:网络
I have to define an association that doesn\'t seem to fit in well to the \"has_one / belongs_to\" bucket very well.

I have to define an association that doesn't seem to fit in well to the "has_one / belongs_to" bucket very well.

The situation is this, I have a table whereby each row corresponds to monthly statistics for a given month and year. I'd love to be able to define certain associations on my model such as record.prior_month or record.prior_year which would correspond to the prior month / year of the current record.

I can't think of any clever way to do this as it doesn't mak开发者_运维问答e any sense to maintain foreign keys that would have to be updated every month for tons of records.

I can always handle the logic in the controller, but I'd prefer to keep it with the model if I could.

Thanks! Mike


So rather than store the Month/Year, also store the Month+Year*12. So March 2011 is 24135

That way, you know the next month is 21436, and you can easily paginate over your records.

TrafficGroup.order("month_calculated").paginate(:page=>params[:page])


Something like this?

class MyModel < AR::Base
  def prior_month
    created_at.month
  end

  def prior_year
    created_at.year
  end
end

example = MyModel.last
example.prior_year
#=> 2010
example.prior_month
#=> 3


You can do this a few ways. Assuming the month is stored in the model.

My favorite is scopes, since it plays nicely with other associations.

For instance you can do:

class TrafficRecord < ActiveRecord::Base
  scope :only_month, lambda {|month| where :month => month} # this should also contain join conditions

  def prior_month
    self.class.only_month(self.month - 1) #decrement your month
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消