我有三個表如何在ActiveRecord中沒有外鍵的情況下定義關係?
prices
timestamp : datetime
unit_id : integer
price : decimal
sales
timestamp : datetime
unit_id : integer
price : decimal
schedules
timestamp : datetime
unit_id : integer
status : string
這些表不屬於任何東西,所以schedules_id或其他鍵將無法正常工作。我怎麼能採取ActiveRecords關係的優勢,得到這樣的:
class Schedules
has_one :sale,
joins: "LEFT OUTER JOIN (sales s)
ON (s.timestamp = schedules.timestamp AND s.unit_id = schedules.unit_id")
has_one :price
...
end
於是我可以
Schedules.where(timestamp: Time.now).includes([:sales, :prices]).all
的現實比上面的例子複雜得多。該應用程序有數百個表。
使用連接工作,但會將屬性/值放入計劃對象中。
class Schedules
def self.prices
select("*").joins("LEFT OUTER JOIN ...")
end
end
上面將在加入prices
字段放入一個時間表工作。
s = Schedules.prices.last # will have a price attribute
s.price
但是,什麼是理想是擁有一個子對象的加入
s.price.price
s.sales.price
如果應用程序有數百個表,那麼您需要重新考慮數據結構。有些東西需要繼承某些東西,或者通過使用類似H-store的東西來減少所需的表的數量http://www.postgresql.org/docs/9.0/static/hstore.html – rovermicrover 2013-04-09 20:14:55