从多个到多个连接表访问对象 - RAILS

时间:2015-08-24 03:37:54

标签: ruby-on-rails database ruby-on-rails-3 ruby-on-rails-4 activerecord

在ActiveRecord / Ruby on Rails中,如果我有这样的多对多关系设置:

class Blog < ActiveRecord::Base
  has_many :tagged_blogposts;
  has_many :tags, through: :tagged_blogposts;
end

class Tag < ActiveRecord::Base
  has_many :tagged_blogposts
  has_many :blogs, through: :tagged_blogposts
end

class TaggedBlogpost < ActiveRecord::Base
  belongs_to :blog
  belongs_to :tag
end

如何选择具有给定tag_id的所有博客?

到目前为止,我有: TaggedBlogposts.all.where(“tag_id =?”,“1”),返回:

+----+---------+--------+-------------------------+-------------------------+
| id | blog_id | tag_id | created_at              | updated_at              |
+----+---------+--------+-------------------------+-------------------------+
| 2  | 1       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 4  | 2       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 7  | 3       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 15 | 6       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 17 | 7       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 24 | 9       | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 33 | 13      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 36 | 15      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 46 | 18      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
| 47 | 19      | 1      | 2015-08-24 03:05:15 UTC | 2015-08-24 03:05:15 UTC |
+----+---------+--------+-------------------------+-------------------------+

但是从这个连接表中,我想返回相应的博客对象。类似的东西:

Blog.all.where(tag_id:1, through: TaggedBlogposts)
编辑:想出来:

@blogs = Blog.joins(:tags).where("tags.id=?", "#{params[:tagid]}")

3 个答案:

答案 0 :(得分:2)

这可以为您提供预期的博客:

Blog.joins('tagged_blogposts').where('tagged_blogposts.tag_id = ?', tag_id)

答案 1 :(得分:0)

尝试以下代码

Blog.inlcudes(:tagged_blogposts).where('tagged_blogposts.tag_id = ?', 1).references(:tagged_blogposts)

答案 2 :(得分:0)

首先查找标签记录:
tag = Tag.find tag_id
然后你可以使用以下方法获取此标签的所有博客:
tag.blogs