我想自定义:
1。首页上的交易顺序
2. 根据用户看到的交易发送电子邮件
感谢SO上的人,似乎最好的是有3个模型和表"standard_user","deals"one_answers"deals_participation",以便具有应用程序需要的多对多关系,一个链接表,如下:
class DealParticipation < ActiveRecord:Base
#This means the deal_participations table has a standard_user_id key
belongs_to :standard_user
#This means the deal_participations table has a deal_id key
belongs_to :deal
#... more logic goes here ...
end
class StandardUser < ActiveRecord::Base
has_many :deal_participations
has_many :deals, :through => :deal_participations
# ... more logic goes here ...
end
class Deal < ActiveRecord::Base
has_many :deal_participations
has_many :standard_users, :through => :deal_participations
belongs_to :admin_user
#... more logic goes here ...
end
我迷失的地方是:我应该如何存储以及我应该查询某个用户参与的哪些交易的数据:
- 我应该存储这个deals_participation_table吗?它的列是deals_participation_id/user_id/deals_id,我担心deals_participation表将是非常无效的查询,因为我将不得不搜索大量的行,找到where user = Mathieu45(示例),然后找到相应的交易,并进行某种计算,以了解他感兴趣的交易类型,然后使用该信息来调整首页上的交易列表(以及发送给他的电子邮件)。
- 我是否应该将其存储在users_table本身中,以便根据user_id直接访问他所做的交易? 将它存储在另一个专用于user_history的表中?
您所描述的模式对于您感兴趣的查询类型非常有效,前提是您在表上放置了正确的索引。数据库的行为不像列表:询问"XXX参与了哪些交易"不应该扫描整个表,因为正确索引的表将确切地知道在哪里找到XXX的所有交易。
为了正确设置,下面是您的迁移的样子:
class CreateStandardUsers < ActiveRecord::Migration
def change
create_table :standard_users do |t|
t.string :name
t.timestamps
# More fields go here
end
add_index :standard_users, :name
end
end
class CreateDeals < ActiveRecord::Migration
def change
create_table :deals do |t|
t.references :admin_user
# other fields go here
end
add_index :deals, :admin_user_id
# other indices go here... anything you want to search on efficiently.
end
end
class CreateDealParticipations < ActiveRecord::Migration
def change
create_table :deal_participations do |t|
t.references :standard_user
t.references :deal
t.timestamps
end
add_index :deal_participations, :standard_user_id
add_index :deal_participations, :deal_id
add_index :deal_participations, :created_at
end
end
仍然有更多属于这些迁移(例如,你应该添加非空约束,唯一性约束等)。关键是这些索引使得你所描述的数据库操作非常快。