给予

时间:2015-06-16 16:27:49

标签: ruby-on-rails-4 activerecord

我使用的是rails 4.2和ruby 2.2

我有以下三个模型

参赛者(设计用户)

Entrant.column_names
=> ["id", "email", "encrypted_password", "reset_password_token", "reset_password_sent_at", "remember_created_at", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "confirmation_token", "confirmed_at", "confirmation_sent_at", "unconfirmed_email", "entrant_name"]

class Entrant < ActiveRecord::Base
   has_many :entries
   has_many :votes, :through => :entries
end

条目

Entry.column_names
 => ["id", "entrant_id", "title_of_work", "price", "created_at", "updated_at", "media_file_name", "media_content_type", "media_file_size", "media_updated_at", "paid", "height", "width", "type_of_media"]

class Entry < ActiveRecord::Base
    belongs_to :entrant
    has_many :votes
    has_many :entrants, :through => :votes
end

投票

Vote.column_names
=> ["id", "entry_id", "judge_id", "score", "created_at", "updated_at"]

class Vote < ActiveRecord::Base
    belongs_to :entry
    belongs_to :judge
end

我需要一个返回下表的查询。我尝试从参赛者开始并加入投票,但没有任何效果。

enter image description here

查询需要提取所有条目,并通过votes.score对votes.score字段和顺序求和,但它也需要按条目分组,以便条目不重复。

这和我一样接近,但它不起作用。

@entries = Entrant.joins(:entries).joins(:votes).select('entrants.*, entries.*, SUM(votes.score) as total_votes').distinct.group('entrants.id, entries.id, votes.score')

1 个答案:

答案 0 :(得分:2)

应该是这样的:

Entry.joins(:entrant).joins(:votes)
                     .group('entries.id')
                     .order('SUM("votes.score")').
                     .pluck(:entrant_name, :title_of_work, 'SUM("votes.score")'),'COUNT("votes.score")')

我在控制台中使用类似的一组关系设置了这个,所以它可能需要一些调整,但它应该让你指向正确的方向。如果你遇到困难,请告诉我。