Finding records in one-to-one association


#1

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


#2

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/Base.html#M000690

-Peter


#3

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/Base.html#M000690

-Peter

Thanks Peter, that helps.