gpt4 book ai didi

sql - Rails 5. 范围链中的错误结果

转载 作者:行者123 更新时间:2023-11-29 13:52:02 25 4
gpt4 key购买 nike

我有下一个模型

用户.rb

class User < ApplicationRecord
has_many :user_tags, dependent: :destroy
has_many :tags, through: :user_tags
has_many :children, foreign_key: 'parent_id', dependent: :destroy

tag.rb

class Tag < ApplicationRecord
has_many :user_tags, dependent: :destroy
has_many :users, through: :user_tags

user_tag.rb

class UserTag < ApplicationRecord
belongs_to :tag
belongs_to :user

child.rb

class Child < ApplicationRecord
belongs_to :parent, class_name: 'User'

在模型用户中,我有几个范围。

选择与所有必需标签关联的用户:

scope :search_by_tags, -> (ids) {
joins(:tags).where(tags: {id: ids}).having('COUNT(tags.id) >= ?', ids.count).group('users.id')
}

生成下一个 SQL 请求

SELECT "users".* FROM "users" INNER JOIN "user_tags" ON "user_tags"."user_id" = "users"."id" INNER JOIN "tags" ON "tags"."id" = "user_tags"."tag_id" WHERE "tags"."id" IN (17, 37, 70, 8, 11, 3, 91, 64) GROUP BY users.id HAVING (COUNT(tags.id) >= 8)

其他范围选择用户,与特定年龄段的 child 相关

scope :children_in_ages, -> (age_ranges) {
joins(:children).where(children_ages_query(age_ranges))
.where.not(children: {gender: -1}).group('users.id')
}

def self.children_ages_query(age_ranges)
child_table = Child.arel_table
range_conditions = age_ranges.map { |r| child_table[:birth_date].in(r) }
range_conditions.inject(range_conditions.shift, &:and).to_sql
end

其中 age_ranges 是日期数组。此作用域生成下一个 SQL 查询:

SELECT "users".* FROM "users" INNER JOIN "children" ON "children"."parent_id" = "users"."id" WHERE ("children"."birth_date" BETWEEN '2016-02-29 08:35:00.322919' AND '2016-08-31 08:35:00.327283') AND ("children"."gender" != $1) GROUP BY users.id

另外,作用域工作正常,但是当我合并作用域时,我得到了错误的结果。

User.children_in_ages(a).search_by_tags(ids)
User Load (85.2ms) SELECT "users".* FROM "users" INNER JOIN "children" ON "children"."parent_id" = "users"."id" INNER JOIN "user_tags" ON "user_tags"."user_id" = "users"."id" INNER JOIN "tags" ON "tags"."id" = "user_tags"."tag_id" WHERE ("children"."birth_date" BETWEEN '2016-02-29 08:35:00.322919' AND '2016-08-31 08:35:00.327283') AND ("children"."gender" != $1) AND "tags"."id" IN (17, 37, 70, 8, 11, 3, 91, 64) GROUP BY users.id HAVING (COUNT(tags.id) >= 8)

任何想法可能是错误的?

最佳答案

我找到了解决问题的方法。

选择具有特定标签的用户的正确方法:

models/user.rb

scope :search_by_tags, -> (ids) { where(id: UserTag.users_with_tags(ids)) unless ids.blank? }

models/user_tag.rb

scope :users_with_tags, -> (ids) {
select(:user_id).where(tag: ids).having('COUNT(user_id) >= ?', ids.count).group('user_id')
}

这样,与其他范围的链接工作正常

关于sql - Rails 5. 范围链中的错误结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39244706/

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