Rails 5.范围链的结果错误

时间:2016-08-31 08:39:45

标签: sql ruby-on-rails ruby postgresql activerecord

我有下一个模特

user.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)

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

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)

任何想法可能出错?

1 个答案:

答案 0 :(得分:0)

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

选择具有特定代码的用户的正确方法:

<强>模型/ user.rb

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

<强>模型/ user_tag.rb

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

通过这种方式,与其他范围链接正常工作