【发布时间】:2015-08-24 03:37:54
【问题描述】:
在 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]}")
【问题讨论】:
标签: ruby-on-rails database ruby-on-rails-3 ruby-on-rails-4 activerecord