2012-03-23 36 views
2

我正在使用Rails應用程序,其中數據之間的關聯隨時間而改變。我創建了一個模型的關聯:取決於時間有和有屬於許多

create_table :accounts_numbers do |t| 
    t.integer :number_id 
    t.integer :account_id 
    t.date :start_date 
    t.date :end_date 

而且,到目前爲止,我有一個簡單的模型,但

class Account < ActiveRecord::Base 
    has_and_belongs_to_many :numbers, :through => accounts_numbers 
end    

代替

@account.numbers 

我需要這樣的東西

@account.numbers_at(Date.new(2010,2,3)) 

我以爲我可以用:conditions,但我不會沒有看到告訴has_and_belongs_to_many創建參數化字段的方法。我也研究過named_scope,但這似乎只是返回帳戶,而不是數字。

更重要的是,這種模式將覆蓋我的代碼中的許多關係,所以會有一種方法可以讓time_dependent_has_and_belongs_to_many全部用完嗎?

回答

1

經過更多的搜索,我終於找到了該做什麼;在/lib DIR我的項目,我創建了一個模塊,TimeDependent

module TimeDependent 
    def at(date) 
     find(:all, :conditions=>["start_date <= ? AND ? < end_date"], date, date) 
    end 
end 

所以,我的模型變得

require "TimeDependent" 
class Account < ActiveRecord::Base 
    has_many :accounts_numbers 
    has_many :numbers, :through => :accounts_numbers, :extend => TimeDependent 
end  

,讓我做什麼我想:

@numbers = @account.numbers.at(Date.new(2010,2,3)); 
0

難道這不是通過編寫Object的函數來完成的嗎?

class Object 
    def numbers_at(time) 
    start = time.to_date 
    end = time.advance(:days => 1).to_date 

    AccountNumber.join(:accounts, :numbers).where("time BETWEEN(?, ?)", start, end) 
    end 
end 
+0

這是「在這裏做某事」我不太確定。我想盡可能地利用ActiveRecord。 – Dave 2012-03-23 20:02:50

+0

好吧,現在它x_x。雖然我假設你在傳遞時間而不是日期。如果你想改變,就問。 – Mizuho 2012-03-23 20:21:49

+0

開始和結束應該是'accounts_numbers'中的字段。這甚至會執行任何連接嗎? – Dave 2012-03-23 20:25:47