Rails 按记录关联查询 [英] Rails query by record association

查看:62
本文介绍了Rails 按记录关联查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Rails 比较陌生,为了了解更多信息,我正在尝试构建一个简单的博客.我遇到的问题之一是标记.我有一个 Tag 模型,用于创建和管理可应用于帖子的标签.我还有一个 Post 模型.我需要能够将任何标签与帖子相关联,检索它们以进行输出,并能够通过特定标签过滤/查询帖子.

I'm relatively new to Rails and to learn more am trying to build a simple blog. One of the issues I'm running in to is tagging. I have a Tag model that I am using to create and manage tags that can be applied to posts. I also have a Post model. I need to be able to associate any of the tags with the post, retrieve them for output, and be able to filter/query posts by a specific tag.

到目前为止,我已经在 Post 上创建了一个名为 tags 的列,它被分配了一个 Tag ID 数组,然后被序列化.这对检索很有用,但我的理解是尝试按序列化列查询记录是 大禁忌.

So far I've created a column on Post called tags, which gets assigned an array of Tag IDs, and is then serialized. This works great for retrieval, but my understanding is that trying to query records by their serialized columns is a big no-no.

正如上面的链接所推荐的,我这样做是为了实现我的过滤器:

As the link above recommends, I've done this to achieve my filter:

Post.all.select { |post| post.tags.include? 3 }

但我知道这是收集所有我的帖子,然后使用数组方法select来过滤它们.

But I know that this is gathering all of my posts and then using the array method select to filter through them.

我的问题是:如何将任意数量的 Tag 记录与 Post 记录相关联,并通过给定的标签查询/过滤 Posts 记录?

My question is: how can I associate any number of Tag records with a Post record, and query/filter Posts records by a given Tag?

推荐答案

让我们假设您的模型如下所示:

So let's assume your models look like this:

class Post < ActiveRecord::Base
  has_many :taggings
  has_many :tags, through: :taggings
end

class Taggings < ActiveRecord::Base
  belongs_to :post
  belongs_to :tag
end

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, through: :taggings
end

因此标记是一种连接模型,可让您与标记和帖子进行多对多关联.

So taggings is the join model that gives you your many-to-many association with tags and posts.

此时,给帖子添加标签就这么简单:

At this point, adding a tag to a post is as simple as:

post.tags << Tag.create(name: 'foo')

您可以通过活动记录查询,在 where 中使用嵌套哈希.

You can query this through active record, by using nested hashes in the where.

Post.joins(:tags).where(tags: { name: 'foo' })

请记住,这里的标签是我们在模型中声明的关系的名称,而不是实际的底层表.所以这实际上要做的是运行看起来像

Remember that tags here is the name of the relationship we declared in the models, not the actual underlying table. So what this is actually going to do is run SQL that looks like

select * from posts
inner join taggings on taggings.post_id = posts.id
inner join tags on taggings.tag_id = tag.id
where tags.name = 'foo';

既然我们已经在模型中声明了表是如何关联的,rails 就知道它必须连接什么才能使用上述代码查询标签.

Since we've declared how the tables are related in the models, rails knows what it has to join together to query tags with the above code.

这篇关于Rails 按记录关联查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆