dc115
dc115

Reputation: 137

How to query all fields from an ActiveRecord model AND one field from its related model

If I have two models foo and bar that are one to many, how could I query all columns from foo and then a single column from bar using Rails query interface?

In other words, how would I translate the below query to Rails:

select foo.*, bar.col from foo inner join bar on foo.bar_id = bar.id;

Upvotes: 0

Views: 976

Answers (1)

asimhashmi
asimhashmi

Reputation: 4378

Assuming you have Foo(with table foos) and Bar(with table bars) as ActiveRecord Models and Foo has many bars

You can make use of joins and select

May be something like this:

Foo.joins(:bars).select("foos.*", "bars.col")

Upvotes: 4

Related Questions