我正在使用merit gem为我的应用程序添加信誉系统。我需要找到用户添加到帖子的点数。我想出的解决方案是将用户在进行投票操作时添加到帖子中的点数相加:
SELECT SUM(num_points)
FROM merit_actions
INNER JOIN merit_activity_logs
ON merit_activity_logs.action_id = merit_actions.id
INNER JOIN merit_score_points
ON merit_score_points.id = merit_activity_logs.related_change_id
INNER JOIN merit_scores
ON merit_scores.id = merit_score_points.score_id
WHERE target_id = post.id
AND target_model = post.class.table_name
AND user_id = post.id
AND sash_id = post.sash_id
这些是与声誉系统相关的表格:
create_table "merit_actions", force: :cascade do |t|
t.integer "user_id"
t.string "action_method"
t.integer "action_value"
t.boolean "had_errors", default: false
t.string "target_model"
t.integer "target_id"
t.text "target_data"
t.boolean "processed", default: false
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "merit_activity_logs", force: :cascade do |t|
t.integer "action_id"
t.string "related_change_type"
t.integer "related_change_id"
t.string "description"
t.datetime "created_at"
end
create_table "merit_score_points", force: :cascade do |t|
t.integer "score_id"
t.integer "num_points", default: 0
t.string "log"
t.datetime "created_at"
end
create_table "merit_scores", force: :cascade do |t|
t.integer "sash_id"
t.string "category", default: "default"
end
从优点库复制的相关模型:
class Action < ActiveRecord::Base
self.table_name = :merit_actions
has_many :activity_logs, class_name: 'Merit::ActivityLog'
end
class ActivityLog < ActiveRecord::Base
self.table_name = :merit_activity_logs
belongs_to :action, class_name: 'Merit::Action'
belongs_to :related_change, polymorphic: true
has_one :sash, through: :related_change
end
class Sash < ActiveRecord::Base
include Base::Sash
has_many :scores, dependent: :destroy, class_name: 'Merit::Score'
end
class Score < ActiveRecord::Base
self.table_name = :merit_scores
belongs_to :sash
has_many :score_points,
dependent: :destroy,
class_name: 'Merit::Score::Point'
def points
score_points.group(:score_id).sum(:num_points).values.first || 0
end
class Point < ActiveRecord::Base
belongs_to :score, class_name: 'Merit::Score'
has_one :sash, through: :score
has_many :activity_logs,
class_name: 'Merit::ActivityLog',
as: :related_change
delegate :sash_id, to: :score
end
end
如何为此目的编写上述SQL查询?