AR query question

Here’s how my associations map:

class Journal < ActiveRecord::Base
has_many :music_journal_entries
has_many :film_journal_entries
end

class FilmJournalEntry < ActiveRecord::Base
belongs_to :journal
end

class MusicJournalEntry < ActiveRecord::Base
belongs_to :journal
end

Both “entries” tables have correct foreign keys set-up and contain
records that map correctly when querying their values through
Journal.

I just want to be able to pull in all of the film_journal_entries and
music_journal_entries buy running an AR query through Journal.

I have tried things like:
all_entries = Journal.all :joins =>
[:music_journal_entries, :film_journal_entries]
and some other things utilizing :include, but I still haven’t got it.

How would I do this?
Thanks!!

Elliott G

On 9 April 2010 19:00, elliottg [email protected] wrote:

Both “entries” tables have correct foreign keys set-up and contain
records that map correctly when querying their values through
Journal.

I just want to be able to pull in all of the film_journal_entries and
music_journal_entries buy running an AR query through Journal.

The easiest way is just:

all_entries = music_journal_entries + film_journal_entries

But it might be worth remodelling your DB a little. It looks to me
like a good candidate for STI to have a single “journal_entries”
table, and then a type of MusicJournalEntry and a type of
FilmJournalEntry (of course, if they’ve got loads of different
properties, you might not want to use STI, but maybe a polymorphic
model would help instead).
That would keep all of a journal’s entries in one table:

class JournalEntry < ActiveRecord::Base
belongs_to :journal
end

class FilmJournalEntry < JournalEntry
end

class MusicJournalEntry < JournalEntry
end

All you need to do to support this is to ensure there’s a string field
in the “journal_entries” table called “type” - Rails handles the rest.

Thanks for the input Michael.

I’ll rethink my data structure a bit.

EG

Elliott G. wrote:

Thanks for the input Michael.

I’ll rethink my data structure a bit.

EG

Your could use Single table inheritance or polymorphic set up if you are
concerned about table getting too large in inheritance…