Rails查询:按另一个表中的属性过滤

时间:2015-03-30 22:26:24

标签: ruby-on-rails ruby

我正在寻找一个清晰的Rails 4示例,介绍如何根据与另一个表相关联的数据来过滤记录。

假设我有一个Users模型和一个Comments模型。用户has_many评论和评论belongs_to用户。评论的表格中还有一个score列。

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       |
| ...                                      |

我如何获得所有对内容发表评论的用户&#34; k&#34;分数&gt; 0?请注意,我想要返回的是用户,而不是评论。


此外,请考虑一个更复杂的示例,其中用户has_many评论和喜欢,评论belong_to用户和评论has_many喜欢。喜欢belong_to用户和belong_to评论。请注意,score不再是此示例中的一个因素。

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          |
| ...                        |

在第二个示例中,我如何找到所有曾经评论过他们的评论的用户,这些用户名为&#39; Fonzie&#39;?

1 个答案:

答案 0 :(得分:5)

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

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

User.joins(:comments) .where("comments.content = ? AND comments.score > ?", 'some_content', 0)

如果您不熟悉上述内容,建议您阅读rails guidelines on queries - 搜索“加入表格”

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