ruby-on-rails – 在Rails 4.2中有很多’finder_sql’替换

我有一个需要一些连接/自定义查询的关联.在试图弄清楚如何实现这个时,重复的响应是finder_sql.但是在Rails 4.2(及以上版本)中:

ArgumentError: UnkNown key: :finder_sql

我进行连接的查询如下所示:

'SELECT disTINCT "tags".*' \
' FROM "tags"' \
' JOIN "articles_tags" ON "articles_tags"."tag_id" = "tags"."id"' \
' JOIN "articles" ON "article_tags"."article_id" = "articles"."id"' \
' WHERE articles"."user_id" = #{id}'

我知道这可以通过以下方式实现:

has_many :tags,through: :articles

但是,如果连接的基数很大(即用户有数千篇文章 – 但系统只有几个标签),则需要加载所有文章/标签

SELECT * FROM articles WHERE user_id IN (1,2,...)
SELECT * FROM article_tags WHERE article_id IN (1,3...) -- a lot
SELECT * FROM tags WHERE id IN (1,3) -- a few

当然也对一般情况感到好奇.

注意:也尝试使用proc语法,但似乎无法弄清楚:

has_many :tags,-> (user) {
  select('disTINCT "tags".*')
    .joins('JOIN "articles_tags" ON "articles_tags"."tag_id" = "tags"."id"')
    .joins('JOIN "articles" ON "article_tags"."article_id" = "articles"."id"')
    .where('"articles"."user_id" = ?',user.id)
},class_name: "Tag"

ActiveRecord::StatementInvalid: PG::UndefinedColumn: ERROR: column tags.user_id does not exist

SELECT disTINCT “tags”.* FROM “tags” JOIN “articles_tags” ON “articles_tags”.”tag_id” = “tags”.”id” JOIN “articles” ON “article_tags”.”article_id” = “articles”.”id” WHERE “tags”.”user_id” = $1 AND (“articles”.”user_id” = 1)

这就是它似乎试图自动将user_id注入标签(并且该列仅存在于文章上).注意:我正在为多个用户预加载,因此无法使用user.tags而无需其他修复(sql粘贴是我正在使用的那个!).思考?

解决方法

虽然这不能直接解决您的问题 – 如果您只需要数据的子集,则可以通过子选择预加载它:
users = User.select('"users".*"').select('COALESCE((SELECT ARRAY_AGG(disTINCT "tags"."name") ... WHERE "articles"."user_id" = "users"."id"),'{}') AS tag_names')
users.each do |user|
  puts user[:tag_names].join(' ')
end

以上是Postgres特定的DB(由于ARRAY_AGG),但其他数据库可能存在等效的解决方案.

另一种选择可能是将视图设置为伪连接表(再次需要数据库支持):

CREATE OR REPLACE VIEW tags_users AS (
  SELECT 
    "users"."id" AS "user_id","tags"."id" AS "tag_id"
  FROM "users"
    JOIN "articles" ON "users"."id" = "articles"."user_id"
    JOIN "articles_tags" ON "articles"."id" = "articles_tags"."article_id"
    JOIN "tags" ON "articles_tags"."tag_id" = "tags"."id"
  GROUP BY "user_id","tag_id"
)

然后你可以使用has_and_belongs_to_many:标签(尚未测试 – 可能想要设置为只读,并且可以删除一些连接并使用,如果你有适当的外键约束设置).

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...