Forum: Ruby Activerecord query question

Posted by Rick Lindal (rjlindal)
on 2012-10-04 22:09
Hi...I am pretty new to activer record.

Struggling with formulating a simple join. I am pretty new to
activerecord and ruby.I have a database with tables 'bugs' and
'longdesc'. Here are my classes:

class Bug < ActiveRecord::Base
  has_many :longdescs
end
class Longdesc < ActiveRecord::Base
  belongs_to :bugs
end
I am trying to formulate a simple query joining these two tables but am
having no luck. I can get a query without joining to work fine. For
example, the following works perfectly:

bugs = Bug.select("bug_id,bug_status,short_desc").where(:bug_id => ARGV)

Now I want to join this with the longdescs table which has column
'thetext' and has bugs.bug_id as the foreign key. Here is the plain ole
sql:

select B.bug_id, B.bug_status, B.short_desc, L.thetext
from bugs B, longdesc L
where B.bug_id in (300,301)
and B.bug_id = L.bug_id


Any assistance would be greatly appreciated!
Posted by Troy Surrett (Guest)
on 2012-10-05 04:19
(Received via mailing list)
Hi Rick,

It's helpful to know which version of ActiveRecord you're using.  Here's
my solution in ActiveRecord 3:

Bug.joins(:longdescs)

The Rails guide to ActiveRecord is very helpful =>
http://guides.rubyonrails.org/active_record_querying.html

From here you can do things like:

Bug.joins(:longdescs).where ...

Hope that helps,
-Troy
Posted by Rick Lindal (rjlindal)
on 2012-10-05 19:44
Troy Surrett wrote in post #1078670:
> Hi Rick,
>
> It's helpful to know which version of ActiveRecord you're using.  Here's
> my solution in ActiveRecord 3:
>
> Bug.joins(:longdescs)
>
> The Rails guide to ActiveRecord is very helpful =>
> http://guides.rubyonrails.org/active_record_querying.html
>
> From here you can do things like:
>
> Bug.joins(:longdescs).where ...
>
> Hope that helps,
> -Troy

Thanks Troy. It is ActiveRecord 3. Here is the solution that worked for
me.
bugs =
Bug.joins(:longdescs).select("bugs.bug_id,bugs.bug_status,bugs.priority,bugs.bug_severity,bugs.short_desc,longdescs.thetext").where(:bug_id
=> ARGV)
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.