Ruby on rails Rails 4有很多过滤功能

Ruby on rails Rails 4有很多过滤功能,ruby-on-rails,Ruby On Rails,我试图弄清楚是否可以通过联接表按记录的属性进行分组/筛选/选择。虽然我知道还有其他方法可以达到同样的效果(我在下面使用其中一种),但我想知道HMT关系是否也可以达到同样的效果 模型如下: class Foo < ActiveRecord::Base has_many :foo_bars has_many :bars, through: foo_bars # SOMETHING LIKE THIS: has_many :group_a_bars, -> where {

我试图弄清楚是否可以通过联接表按记录的属性进行分组/筛选/选择。虽然我知道还有其他方法可以达到同样的效果(我在下面使用其中一种),但我想知道HMT关系是否也可以达到同样的效果

模型如下:

class Foo < ActiveRecord::Base
  has_many :foo_bars
  has_many :bars, through: foo_bars

  # SOMETHING LIKE THIS:
  has_many :group_a_bars, -> where { foo_bars.bar.bar_group_id: 1 }
end

class Bar < ActiveRecord::Base
  # == Schema Information
  #
  # Table name: bars
  # bar_group_id :integer          not null

  belongs_to :bar_group
end

class FooBar < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end

class BarGroup < ActiveRecord::Base
  has_many :bars
end
编辑:按照@smathy的建议,我添加了一个连接,并使其与以下内容一起工作:

class Foo < ActiveRecord::Base
  has_many :foo_bars
  has_many :bars, through: foo_bars

  # WORKING:
  has_many    :group_a_bars,
                ->              { joins(:bar).where(bars: { bar_group_id: 1 }) },
                class_name:     "FooBar",
                source:         :bar
end
class Foo{连接(:bar)。其中(bar:{bar\u group\u id:1}),
类名:“FooBar”,
source::bar
结束

是的,它将是这样的:

has_many :group_a_bars,
  -> { joins(:bar).where( bar: { bar_group_id: 1 } ) }, through: :foo_bars, class_name: "Bar"
您可能还需要一个
:source
选项

has_many :group_a_bars,
  -> { joins(:bar).where( bar: { bar_group_id: 1 } ) }, through: :foo_bars, class_name: "Bar"