ruby-on-rails – 在Rails 4.2中有很多’finder_sql’替换
我有一个需要一些连接/自定义查询的关联.在试图弄清楚如何实现这个时,重复的响应是finder_sql.但是在Rails 4.2(及以上版本)中:
我进行连接的查询如下所示: '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"
这就是它似乎试图自动将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:标签(尚未测试 – 可能想要设置为只读,并且可以删除一些连接并使用,如果你有适当的外键约束设置). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |