【问题标题】:Rails acts_as_taggable - tagged_with through a relationRails act_as_taggable - 通过关系标记_with
【发布时间】:2015-09-19 08:11:20
【问题描述】:

假设我有一个像这里的例子一样的用户/帖子模型:

https://github.com/mbleigh/acts-as-taggable-on#tag-cloud-calculations

用户有很多帖子,帖子属于用户。帖子有标签。我可以轻松搜索拥有特定标签帖子的用户吗?

【问题讨论】:

    标签: ruby-on-rails activerecord acts-as-taggable-on


    【解决方案1】:

    所以你基本上有:

    class User
      has_many :posts
    end
    
    class Post
      acts_as_taggable
    
      # under the hood, this declaration creates
      # following relations
      has_many :tags
      has_many :taggings
    end
    

    您现在可以将以下关系添加到User

    class User
      has_many :posts
      has_many :tags, through: :posts
      # has_many :taggings, through: :posts
    end
    

    现在查询给定的@tag 应该很容易:

    users_with_give_tag = User.joins(:tags).where("tags.id=?", @tag.id)
    

    产生以下 SQL:

    SELECT "users".* FROM "users"
    INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
    INNER JOIN "taggings" ON "taggings"."taggable_id" = "posts"."id" AND "taggings"."context" = ? AND "taggings"."taggable_type" = ?
    INNER JOIN "tags" ON "tags"."id" = "taggings"."tag_id"
    WHERE (tags.id=1)  [["context", "tags"], ["taggable_type", "Post"]]
    

    【讨论】:

    • 成功了。我遇到了问题,因为在我的第一次迭代中,我的用户模型中有acts_as_taggable 启动,这导致结果为零。
    • 如何扩展对多个标签的搜索? Like , 查找帖子被标记为“a”和“b”的用户
    猜你喜欢
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多