【问题标题】:Rails find with three tables and a SUM operationRails 使用三个表和一个 SUM 操作查找
【发布时间】:2010-08-12 06:32:28
【问题描述】:

我有点难以通过查找操作来获得我想要的记录顺序。

假设您有三个模型: 1. 网站 2. 链接 3. 投票

一个网站有很多链接,一个链接有很多投票。每张投票都有一定数量的点数,用户可以将这些点数归于该投票。我正在尝试获取一个网站索引页面,其中的网站按照他们为该网站的所有链接收到的积分总和的顺序列出。

这是架构的简化版本

  create_table "votes", :force => true do |t|
    t.integer  "link_id"
    t.integer  "points"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"

  end

  create_table "links", :force => true do |t|
    t.string   "name"
    t.string   "link"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.integer  "votes_count", :default => 0
    t.integer  "website_id"
  end

  create_table "websites", :force => true do |t|
    t.string   "domain"
    t.boolean  "verified",          :default => false
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

我正在考虑在这里使用正确的活动记录查询。任何帮助将不胜感激。

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案1】:

    在我发布这个问题仅仅一个小时后想出一个解决方案时,我想我花了一天的时间才想出一个解决方案。

    在网站模型中我把网站has_many :points, through => :links

    然后查询:

    array = Website.find(:all)
    
    array.sort_by {|w| w.donations.sum('amount')}.reverse
    

    这似乎行得通。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多