【发布时间】:2012-08-12 05:35:19
【问题描述】:
我的 Rails 应用程序是一个用户在彼此之间交易项目的系统。用户对项目出价,然后所有者批准创建交易的出价。然后,用户可以在事务上编写 cmets(消息)来组织应用程序之外的事物。到目前为止,我的结构是这样的:
User
has_many :items
has_many :bids
Item
belongs_to :user
has_many :bids
Bid
belongs_to :item
belongs_to :user
has_one :transaction
Transaction
belongs_to :bid
has_many :messages
Message
belongs_to :transaction
belongs_to :from, :class_name => "User"
belongs_to :to, :class_name => "User"
我认为这在减少冗余方面效果很好,但我在有效地获取数据方面遇到了一些问题。例如,要检索user 的“给定项目”(即其中一个投标存在交易的用户项目),我正在做:
user.items.joins(:bids).where("bids.id" => Transaction.select("bid_id"))
或收到的物品:
Item.joins(:bids).where("bids.user_id" => user.id).where("bids.id" => Transaction.select("bid_id"))
这对于我想要的信息来说似乎相当昂贵。
更重要的是,我想汇总用户的交易并显示给定物品与收到物品的比率,这可能会显示在任何给定页面上的用户名旁边。目前我正在做的是获取并计算所有用户在上面给出和接收的项目,然后除以(这是非常昂贵的......)。我想在 User 表上设置一个带有 received_count 和 given_count 的列,每次创建或销毁事务时都会更新,但这似乎不可靠。
我的问题是,有没有更好的方法来构建我的数据,以便更简单地获取用户交易等信息,同时保持标准化?
谢谢!
【问题讨论】:
标签: mysql ruby-on-rails database postgresql activerecord