kolosy
kolosy

Reputation: 3099

RoR: select join model by condition on child table

I've got the following schema:

foo:
  id: integer

bar:
  id: integer
  condition: boolean

foo_bar:
  id: integer
  foo_id: integer
  bar_id: integer

Both model and schema look like this. Given an instance of foo, I'd like to get an instance of foo_bar where the corresponding bar.condition is true.

Is there a RoR-friendly way to do this?

Upvotes: 0

Views: 76

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

You might wish to consider ActiveRecord Association Extensions:

#app/models/foo.rb
class Foo < ActiveRecord::Base
   has_many :foo_bar
   has_many :bar, through: :foo_bar do
      def true
         where condition: true
      end
   end
end

#app/models/foo_bar.rb
class FooBar < ActiveRecord::Base
   belongs_to :foo
   belongs_to :bar
end

#app/models/bar.rb
class Bar < ActiveRecord::Base
   has_many :foo_bar
   has_many :foo, through: :foo_bar
end

This will give you the ability to call the following:

@foo = Foo.find x
@foo.bar.true

Although this won't call the foo_bar records themselves, if you work it correctly, you should be able to load the data you require

Upvotes: 0

infused
infused

Reputation: 24337

First, you need to setup some ActiveRecord associations:

class Foo < ActiveRecord::Base
  has_many :foo_bars
end

class Bar < ActiveRecord::Base
  has_many :foo_bars
end

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

Then you can query those associations. Given an instance of Foo, find the first instance of FooBar where bar.name == 'my-bar':

foo = Foo.find(1)
foo.foo_bars.include(:bar).where(bar: {name: 'my-bar'}).first

Upvotes: 1

Related Questions