【问题标题】:Accessing objects from many to many join table - RAILS从多对多连接表访问对象 - RAILS
【发布时间】: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


    【解决方案1】:

    这应该会给你预期的博客:

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

    【讨论】:

    • tagged_blog_posts 应该是tagged_blogposts
    • 谢谢 - 我刚刚用另一个有效的答案编辑了我的 q (基本上与标签表连接的内容相同)。也就是说,我认为使用任一表都没有区别 - 正确吗?
    • 是的,同样的事情。该查询和我的查询应该给出相同的结果。
    【解决方案2】:

    试试下面的代码

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

    【讨论】:

      【解决方案3】:

      首先找到标签记录:
      tag = Tag.find tag_id
      然后您可以使用以下命令获取此标签的所有博客:
      标签.blogs

      【讨论】:

        猜你喜欢
        • 2017-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        相关资源
        最近更新 更多