ruby on rails - What join/model arrangement would be appropriate here? -
i've been reading on various types of relationships possible under activerecord, , i'm in position think understand details in abstract haven't clicked me. appreciate little advice on issue.
in practice application, dealing 4 concrete things: viewers, tv shows, discs of shows, , episodes. there's 1 abstract thing, viewer<->show or 'subscription'/'who watches what' relationship, run trouble.
summary
- each
owner
watches severalshow
s. - each
show
has manyepisode
s. - an
episode
belongs 1show
. - an
owner
owns manydisc
s. - a
disc
belongs show, has manyepisode
s on it. - the same
disc
can owned manyowner
s, there needs way see ifowner
owns specificdisc
-- fact watchshow
disc
belongs isn't enough, there has boolean 'owned?' somewhere.
i need pull data out neatly answer questions like:
- what shows user x watch?
- who watches show y?
- how many discs user x own?
- what episodes on disc z?
- what episodes not on discs yet?
- does user x not own discs of shows watch?
my best guess
subscription
belongs_to :owner
,belongs_to :show
- join table,
subscriptions
, 2 columns:t.references :owner
,t.references :show
owner
has_many :discs
,has_many :shows, through: :subscriptions
show
has_many :discs
,has_many :owners, through: :subscriptions
show
has_many :episodes
episode
belongs_to :show
,belongs_to :disc
disc
has_many :episodes
,belongs_to_many :owners
problem
it's fuzzy , jumbled around in head, , i'm not sure using join table or if it's proper use has_and_belongs_to_many
. i've mocked couple of times today, combination of trying nail queries , unfamiliar syntax , trying grasp or create relationships leading frustration , confusion. i'd appreciate pointing out mistake i've made, letting me know 'railsy' way this, or explaining proper relationship structure should be.
here i'd do:
owner:
has_many: subscriptions has_many: disks, through: :subscriptions
show:
has_many :episodes has_many :disks
episode:
belongs_to :show belongs_to :disk
disk:
belongs_to :show has_many :subscriptions has_many :owners, through: :subscriptions has_many :episodes
subscription:
belongs_to: owner belongs_to: disk
that should work. thing isn't there owner-show relationship. , think best, since there isn't real-life connection. real connection through disks (if don't own disks of show, don't watch show). can shows owner
watches (and visa-versa) by:
@shows = @owner.disks.map(&:show).flatten.uniq @owners = @show.disks.map(&:owners).flatten.uniq
those last 2 lines untested, believe should work fine.
Comments
Post a Comment