Rails 3 ActiveRelation 添加“is null”在加入...我如何阻止它这样做?

发布于 2024-11-04 20:26:32 字数 764 浏览 0 评论 0原文

我正在尝试我的第一次连接,它生成的 sql 非常奇怪。

我有一个属于用户的收件人。我正在尝试查询用户的所有收件人,这些收件人也未被读取且未被删除:

scope :unread, where(:is_read => false).where(:is_deleted => false)
scope :unread_by_user_id, lambda { |id| unread.joins(:user).merge(User.by_id(id)) }

这是它生成的sql:

SELECT `recipients`.* FROM `recipients` INNER JOIN `users` ON `users`.`id` IS NULL WHERE `recipients`.`is_read` = 0 AND `recipients`.`is_deleted` = 0 AND `users`.`id` = 475

有什么方法可以摆脱“IS NULL”吗?那不应该在那里 :(

我尝试在 google 上搜索,令人惊讶的是 95% 的示例都没有谈论联接。我发现的少数几个联接示例使用了已被弃用的 & 语法与其他东西相比,这方面的文档实际上非常糟糕,无论如何

,当你开发软件 19 年却无法实现这一点时,这绝对不是一个好日子。 sql 连接到单个表:( 我可以手动在 sql 中编写具有 15 个连接的查询,没有问题。我想这就是您在学习新框架时有时要付出的代价。尽管在 Hibernate 中,这并不奇怪:/

I am trying my first join and the sql that it's generating is very odd.

I have a Recipient belongs to a User. I am trying to query all the recipients by a user that are also not read and not deleted:

scope :unread, where(:is_read => false).where(:is_deleted => false)
scope :unread_by_user_id, lambda { |id| unread.joins(:user).merge(User.by_id(id)) }

This is the sql it generates:

SELECT `recipients`.* FROM `recipients` INNER JOIN `users` ON `users`.`id` IS NULL WHERE `recipients`.`is_read` = 0 AND `recipients`.`is_deleted` = 0 AND `users`.`id` = 475

Is there any way I can get rid of the "IS NULL"? That's not supposed to be there :(

I have tried searching google, and it's actually really amazing that 95% of examples out there do not talk about joins. The few examples of joins that I do find use the & syntax that has become depreciated. The documentation for this is actually quite bad compared to other things. Very odd indeed.

Anyway, I can't get this to work. It's definitely not a good day when you've been developing software for 19 years and can't get sql to join on a single table :( I can write queries in sql with 15 joins no problem manually. I guess that's the price you pay sometimes when you go through and learn new frameworks. It's not this weird though in Hibernate :/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小嗷兮 2024-11-11 20:26:32

假设您已获取用户:

user.recipients.unread

收件人关联已将收件人限制为该用户。对此有一个单独的范围对我来说没有意义。

--edit

如果您的用户模型定义了 has_many :recipients 关联,则此方法有效。

Assuming you have your user fetched already:

user.recipients.unread

Recipients association already limits recipients to that user. Having a separate scope for that doesn't make sense to me.

--edit

This works if your User model has has_many :recipients association defined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文