根据用户历史自定义交易应用程序的主页和电子邮件:如何在Rails / postgreSQL上以正确的方式执行此操作?

我想定制:

1.主页上的交易顺序
2.电子邮件取决于用户看到的交易。

感谢SO上的人 ,似乎最好的是拥有3个模型和表“standard_user”,“deals”和“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  :deal_participations # ... more logic goes here ... end class Deal  :deal_participations belongs_to :admin_user #... more logic goes here ... end 

我丢失的地方是:我应该如何存储以及应该在哪个表中查询某个用户参与的交易的数据:

  • 我应该存储此deals_participation_table吗? 它的列是deals_participation_id / user_id / deals_id,我担心deal_participation表对查询非常无效,因为我将不得不搜索大量的行,找到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 

在这些迁移中还有更多属于它们(例如,您应该添加非空约束,唯一性约束等)。 但重点是拥有这些索引会使您描述的数据库操作速度极快。