我有一个用户模型,它有_many 投资组合,它有_many 资产,它有_and_belongs_to_many AssetHistories。
基本上,用户 1 的投资组合中可能有 Google,而用户 2 的投资组合中可能也有 Google。当我可以拥有多对多 (HABTM) 关系时,为什么要使用重复的 Google 股票价格历史行填充数据库。然而,让我失望的是当asset_id 是多个值时,在 AssetHistory 模型中放置什么。即它需要同时引用用户1 和用户2。用户1 的Google 可能是asset.id 1,用户2 的Google 可能是asset.id 2。因此,AssetHistory 模型中的条目如何引用这两个ID?
很明显,asset_id 不能同时为 2 个值,但我无法理解这一点。我应该使用 aforeign_key
并使 Google 成为密钥吗?如果是这样,我的资产模型中仍然存在问题,即为 Asset_History_id 放置什么条目,因为资产 Google 可能有 30 行股票价格历史记录。每个股票价格历史都是不同的 Asset_History_id。
有人可以帮助解释我做错了什么吗?
请注意,我在资产模型中使用 after_save 来填充资产价格历史记录。即当有人添加资产时,它会填充asset_history,但它不会填充Asset 模型中的asset_history_id 字段,也不会填充AssetHistory 模型中的asset_id,因为我不知道在那里做什么。
我的资产模型有:
class Asset < ActiveRecord::Base
attr_accessible :asset_symbol, :shares, :cost, :date_purchased, :asset_history_id
belongs_to :portfolio
has_and_belongs_to_many :asset_histories
after_save populatepricehistory
private
def populatepricehistory
#uses an api to download price data as an array and imports it to AssetHistory...
#I expect something should go here to fill out the asset_history_id field in the Asset Model
#while simultaneously filling out the asset_id in the AssetHistory model
end
end
资产历史模型
class AssetHistory < ActiveRecord::Base
attr_accessible :close, :date, :asset_id, :asset_symbol
has_and_belongs_to_many :assets
end
AssetHistoryAsset 连接表的迁移
class AssetHistoryAssetJoinTable < ActiveRecord::Migration
def up
create_table :asset_histories_assets, :id=> false do |t|
t.integer :asset_id
t.integer :asset_history_id
end
end
def down
drop_table :asset_histories_assets
end
end