gpt4 book ai didi

ruby-on-rails - 带条件求和的 PostgreSQL 语法,使用 Rails

转载 作者:行者123 更新时间:2023-11-29 14:20:52 26 4
gpt4 key购买 nike

我有两个 postgresql 表:User 和 QualifyingEvents。我正在尝试获取特定用户的 QualifyingEvents 中一列的总和,特别是 current_user(由设计定义)。

我正在尝试在 ROR 项目中定义“hours_total”。

此查询有效:

QualifyingEvent.sum(:hours_earned)

这个查询没有:

QualifyingEvent.sum(:hours_earned, :conditions => {"user_id = ?", id})

“过滤”特定用户的合适方法是什么,特别是登录的 current_user。

这是我的 Rails schema.rb 文件(已简化):

ActiveRecord::Schema.define(version: 20141220001323) do

# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"

create_table "admins", force: true do |t|
-- NOT RELEVANT, NOT SHOWING --
end

add_index "admins", ["email"], name: "index_admins_on_email", unique: true, using: :btree
add_index "admins", ["unlock_token"], name: "index_admins_on_unlock_token", unique: true, using: :btree

create_table "qualifying_events", force: true do |t|
t.string "course_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "hours_earned"
-- NOT RELEVANT, NOT SHOWING --
end

add_index "qualifying_events", ["user_id", "created_at"], name: "index_qualifying_events_on_user_id_and_created_at", using: :btree
add_index "qualifying_events", ["user_id"], name: "index_qualifying_events_on_user_id", using: :btree

create_table "users", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"

-- NOT RELEVANT, NOT SHOWING --
end

add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true, using: :btree
add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true, using: :btree

end

还有,除了 ActiveRecord::Calculations http://api.rubyonrails.org/v3.2.5/classes/ActiveRecord/Calculations.html 之外,还有什么好的资源吗? - 用于 PostgreSQL 和 ROR 语法。预先感谢您的帮助!

最佳答案

QualifyingEvent.where(user_id: current_user.id).sum(:hours_earned)

如果您已经建立了正确的关联,那么以下内容会更好:

current_user.qualifying_events.sum(:hours_earned)

关于ruby-on-rails - 带条件求和的 PostgreSQL 语法,使用 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com