加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails查询:按另一个表中的属性过滤

发布时间:2020-12-17 03:17:59 所属栏目:百科 来源:网络整理
导读:我正在寻找一个清晰的Rails 4示例,介绍如何根据与另一个表相关联的数据来过滤记录. 假设我有一个Users模型和一个Comments模型.用户has_many评论,评论属于用户.评论在其表格中也有一个分数列. class User ActiveRecord::Base has_many :commentsend Users| id
我正在寻找一个清晰的Rails 4示例,介绍如何根据与另一个表相关联的数据来过滤记录.

假设我有一个Users模型和一个Comments模型.用户has_many评论,评论属于用户.评论在其表格中也有一个分数列.

class User < ActiveRecord::Base
  has_many :comments
end
Users
| id  | name    | email               |
|-----|---------|---------------------|
| 1   | "Alice" | "alice@example.com" |
| 2   | "Bob"   | "bob@example.com"   |
| ...                                 |
class Comment < ActiveRecord::Base
  belongs_to :user
end?

 Comments
| id  | score | content          | user_id |
|-----|-------|------------------|---------|
| 1   | 0     | "lol"            | 2       |
| 2   | 2     | "more like love" | 3       |
| ...                                      |

我如何获得所有使用内容“k”发表评论并且分数> gt的用户? 0?请注意,我想要返回的是用户,而不是评论.

另外,请考虑一个更复杂的示例,其中用户has_many评论和喜欢,评论属于用户,评论has_many喜欢.喜欢属于用户并且属于评论.请注意,在此示例中,分数不再是一个因素.

class User < ActiveRecord::Base
  has_many :comments
  has_many :likes
end
Users
| id  | name    | email               |
|-----|---------|---------------------|
| 1   | "Alice" | "alice@example.com" |
| 2   | "Bob"   | "bob@example.com"   |
| ...                                 |
class Comment < ActiveRecord::Base
  belongs_to :user
  has_many :likes
end
Comments
| id  | content          | user_id |
|-----|------------------|---------|
| 1   | "lol"            | 2       |
| 2   | "more like love" | 3       |
| ...                              |
class Like < ActiveRecord::Base
  belongs_to :user
  belongs_to :comment
end
Likes
| id  | user_id | comment_id |
|-----|---------|------------|
| 1   | 1       | 2          |
| 2   | 4       | 3          |
| ...                        |

在第二个示例中,我如何找到所有曾经有一个用户名为“Fonzie”的用户喜欢的用户?

解决方法

回答你的第一个问题.您需要创建一个新的表格结构,引用用户和评论表之间的关联.

这可以通过User.joins(:comments)来实现.现在,您有一个包含所有用户及其相关注释的表.要应用过滤器,您只需执行以下操作:

User.joins(:评论)
??.where(“comments.content =?AND comments.score>?”,“some_content”,0)

如果你不熟悉上述内容,我建议你阅读rails guidelines on queries – 搜索’加入表’

由于第二个例子有点复杂,我建议您先熟悉上面的指南.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读