using multiple joins in queries

15 views
Skip to first unread message

John Merlino

unread,
Mar 20, 2013, 6:04:16 PM3/20/13
to Ruby on Rails: Talk
I have this query:

Report.
joins(:alerts).
joins(:alert_code).
where(:unit_id => unit_id).
where{time < my{self.time}}.
where("alert_codes.name LIKE ?", "%Inside virtual
fence%").
order("reports.time DESC").first

Basically, it breaks:

ActiveRecord::ConfigurationError (Association named 'alert_code' was
not found; perhaps you misspelled it?):


My associations look like this:

report has_many alerts
alert belongs_to :alert_code, :foreign_key => :code

I am trying to get the first report whose alerts belongs to alert_code
whose name is "inside virtual fence". So there are 3 associations
here. Trying to establish the connection.

Rob Biedenharn

unread,
Mar 20, 2013, 10:33:24 PM3/20/13
to rubyonra...@googlegroups.com

On Mar 20, 2013, at 6:04 PM, John Merlino wrote:

> I have this query:
>
> Report.
> joins(:alerts).
> joins(:alert_code).

I think that you're looking for 'includes' rather than 'joins' for these associations.

Report.includes({:alerts => :alert_code}).

To use joins, you would have to supply more SQL-ish clauses, not symbols for the associations.

http://apidock.com/rails/v3.2.8/ActiveRecord/QueryMethods/joins
http://apidock.com/rails/v3.2.8/ActiveRecord/QueryMethods/includes

-Rob
> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
> To post to this group, send email to rubyonra...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Frederick Cheung

unread,
Mar 21, 2013, 5:38:50 AM3/21/13
to rubyonra...@googlegroups.com
On Thursday, March 21, 2013 2:33:24 AM UTC, Rob Biedenharn wrote:

On Mar 20, 2013, at 6:04 PM, John Merlino wrote:

> I have this query:
>
> Report.
>                    joins(:alerts).
>                    joins(:alert_code).

I think that you're looking for 'includes' rather than 'joins' for these associations.

Report.includes({:alerts => :alert_code}).


To use joins, you would have to supply more SQL-ish clauses, not symbols for the associations.

joins accepts either association names or sql clauses. When passing association names the syntax is the same as for includes, in particular you have to specify nested associations as a hash (as you have done).

Fred
Reply all
Reply to author
Forward
0 new messages