AR query question

Here's how my associations map:

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

class FilmJournalEntry < ActiveRecord::Base
belongs_to :journal

class MusicJournalEntry < ActiveRecord::Base
belongs_to :journal

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

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?

Elliott G

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

class FilmJournalEntry < JournalEntry

class MusicJournalEntry < JournalEntry

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.


Elliott Golden wrote:

Thanks for the input Michael.

I'll rethink my data structure a bit.


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