Forum: Ruby on Rails Finding records in one-to-one association

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8217faf2bfdfa7daf10135d41ddd421e?d=identicon&s=25 Jeff Cohen (jeff)
on 2005-11-30 03:58
Hope this question isn't too strange.  I have a feeling the answer is
obvious yet it's eluding me.  My actual situation is complicated, but I
think I can fabricate a simple example to demonstrate my problem.

Suppose I have two tables:

table: musicians
columns: id (int), name (text), haircolor (text)

table: stats
columns: id (int), musician_id (int), concerts (int), albums (int)

And obviously the Ruby code looks like:

class Musician < ActiveRecord::Base
  has_one :stat

class Stat < ActiveRecord::Base
  belongs_to :musician

Whew.  Ok, so here's the question.  How do I get a list of all the stat
records for musicians of a given haircolor?

I'd like to do something like:

 Stat.find_by_musician_haircolor("red") => array of stat objects

but I don't think the dynamic finders can "reach into" the parent table
like that.

I suppose I could do

  Stat.find(:all).delete_if { |stat| stat.musican.haircolor != "red" }

but that's pretty inefficient for the database.

Any ideas?  Am I missing something obvious about Rails?

Thanks!
Jeff
Eea3feaacbe44706164289d068d94828?d=identicon&s=25 petermichaux (Guest)
on 2005-11-30 04:09
(Received via mailing list)
I think you would do

musicians = Musician.find(:all, :conditions => "haircolor = 'blond'")

musicians.each do |musician|
  musician.stats.concerts
end

To make the find more efficicient you could use the :include option. see

http://api.rubyonrails.com/classes/ActiveRecord/Ba...

-Peter
8217faf2bfdfa7daf10135d41ddd421e?d=identicon&s=25 Jeff Cohen (jeff)
on 2005-11-30 16:00
petermichaux wrote:
> I think you would do
>
> musicians = Musician.find(:all, :conditions => "haircolor = 'blond'")
>
> musicians.each do |musician|
>   musician.stats.concerts
> end
>
> To make the find more efficicient you could use the :include option. see
>
> http://api.rubyonrails.com/classes/ActiveRecord/Ba...
>
> -Peter

Thanks Peter, that helps.
This topic is locked and can not be replied to.