【问题标题】:Rails acts as taggable on, get all related objects that have a certain tagRails 充当可标记对象,获取所有具有特定标记的相关对象
【发布时间】:2015-05-14 10:06:46
【问题描述】:

FooBar 之间存在 n 对 n 关系,并且 Bar 是一个可标记对象。

class Foo < ActiveRecord::Base
  has_many :xx
  has_many :bars, through: :xx
end

class Bar < ActiveRecord::Base
  has_many :xx
  has_many :foos, through: :xx
  acts_as_taggable
end

我正在使用acts as taggable on gem;我想知道是否有办法使用tagged_with 获取所有 Foo 对象,这些对象的 Bar 对象标记为某个标签

例子:

Foo.with_bar_tagged_with("input_search_tag")
#=> #<ActiveRecord::Relation [#<Foo>,...]

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 tags acts-as-taggable-on


    【解决方案1】:

    这不是我的想法,但我期待类似的东西。

    def Foo.with_bar_tagged_with(tag)
      Bar.tagged_with(tag).collect{|x|x.bars}.flatten.uniq
    end
    

    【讨论】:

    • 我认为应该是x.foos 而不是x.bars。您的回答还可以,但有一些问题(完成的查询太多)。查看我的答案(使用 Squeel)
    【解决方案2】:

    最终使用以下方法解决:

    Foo.joins(:bars).where("bars.id IN ?",Bar.tagged_with("input_search_tag")).uniq
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 2020-07-23
      • 2015-06-10
      • 1970-01-01
      相关资源
      最近更新 更多