mysql - Rails 使用连接关联提取值

标签 mysql ruby-on-rails ruby-on-rails-4 join activerecord

我在 2 个模型 superherosuperpower 之间有一个 Rails 连接表。现在我有 3 个不同的 superpower id 我想要所有 superheroes 都具有所有选定的 superpowers

为此,我正在尝试执行以下操作:

matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id = ?', 17).where('superpowers.id = ?', 12).where('superpowers.id = ?', 6)

但这给了我一个空对象,即使我有 superheroes 在我的连接表中有所有给定的 superpowers

从上面生成的查询是:

SELECT "superheroes".* FROM "superheroes" INNER JOIN "superheroes_superpowers" ON "superheroes_superpowers"."superhero_id" = "superheroes"."id" INNER JOIN "superpowers" ON "superpowers"."id" = "superheroes_superpowers"."superpower_id" WHERE (superpowers.id = 17) AND (superpowers.id = 17) AND (superpowers.id = 12) AND (superpowers.id = 6)

奇怪的是,它尝试检查 id 为 17 的 superpower 两次(但我认为它不应该影响结果)并且查询的其余部分似乎是正确的。

最佳答案

尝试使用 in 子句

superpowers_ids = [17,12,6]
matches = Superhero.all
matches = matches.joins(:superpowers).where('superpowers.id in (?)', superpowers_ids)

关于mysql - Rails 使用连接关联提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46144962/

相关文章:

ruby-on-rails - controller.js.coffee 中的函数

ruby-on-rails - 搜索没有最后一个的事件记录

mysql - 数据库大小会影响 mysql 中的插入时间吗?

php - 如何在不刷新页面的情况下从数据库字段更新页面上的文本?

mysql - 存储 1TB 数据的数据库软件

ruby-on-rails - 覆盖 Rails Paperclip 插件的 content_type

javascript - rails I18n-js : missing translation

ruby-on-rails-4 - Rails/ unicorn 错误: can't read secret_key_base and secret_token from "config/secrets.yml"

ruby-on-rails - 重用 minitest 集成测试

php - MySQL 插入损坏