【问题标题】:Rails or SQL query to fetch user association dataRails 或 SQL 查询以获取用户关联数据
【发布时间】:2020-08-05 01:49:32
【问题描述】:

我有以下三个模型(每个字段在 # 之后):

class User < ApplicationRecord
  has_many :user_tags, dependent: :destroy
end

class UserTag < ApplicationRecord
  belongs_to :user
end

class JourneyTag < ApplicationRecord
  belongs_to :journey
end

我想查找所有带有与用户标签相对应的标签的旅程 - user.user_tags。如何获取这些数据?

我想做什么:

current_user.user_tags.each do |user_tag|
  JourneyTag.where(cms_tag_id: user_tag.cms_tag_id)
end

这应该给我与user.user_tags 相同的cms_tag_id 的JourneyTag,然后我想抓住这个JourneyTag 的集合来查找Journey。但是上面的查询没有用,因为它总是返回一些 JourneyTag,即使它与 user_tag.cms_tag_id 不匹配也是如此。

【问题讨论】:

  • 为了调试,您可以将这些行添加到puts user_tag.cms_tag_id; puts JourneyTag.where(cms_tag_id: user_tag.cms_tag_id).to_sql上方的块查询中
  • 您忘记添加旅程模型了。

标签: sql ruby-on-rails ruby


【解决方案1】:

试试:

Journey.joins(:journey_tags).where(journey_tags: { cms_tag_id: current_user.user_tags.pluck(:cms_tag_id) })

分解:

current_user.user_tags #=> returns all user tag ids associated 
current_user.user_tags.pluck(:cms_tag_id) #=> gives all associated cms_tag_id in single SELECT `cms_tag_id` query 
journey_tags: { cms_tag_id: current_user.user_tags.select(:cms_tag_id) } #=> executes matching WHERE against JourneyTags
Journey.joins(:journey_tags) #=> filtered JourneyTags joins with Journey

或者,您可以尝试以下手动连接:

Journey.joins(:journey_tags).joins('INNER JOIN user_tags on user_tags.cms_tag_id = journey_tags.cms_tag_id INNER JOIN users on user_tags.user_id = users.id')

【讨论】:

  • 在我的脑海中,您应该能够select(:cms_tag_id) 而不是pluck(:cms_tag_id) 以便执行嵌套查询而不是双重查询。
  • @Kache 谢谢!直到。我不知道 select 会在单个查询中懒惰地转换它!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多