0

I basically want to setup a relationship similar to Netflix's DVD rental model.

There are users, and each user has a queue, each queue contains many DVDs and DVDs can have many queues. A queue belongs to a user.

I'm not quite sure how to set this up in active record. I thought maybe a queue and a user should be a has_many :through relationship but that doesn't make much sense.

Any help is appreciated!

Matthew Berman
  • 8,481
  • 10
  • 49
  • 98

1 Answers1

1
class User < ActiveRecord::Base
  has_many :queues
end

class Queue < ActiveRecord::Base
  belongs_to :user
  has_many :dvd_queues
  has_many :dvds, through: :dvd_queues
end

class Dvd < ActiveRecord::Base
  has_many :dvd_queues
  has_many :queues, through: :dvd_queues
end

class DvdQueue < ActiveRecord::Base
  belongs_to :dvd
  belongs_to :queue
end

The benefit of using has_many instead of has_and_belongs_to_many associations between Dvd & Queue is that this allows you to add fields, like priority, to DvdQueue.

which models need views and controllers if i want the user to be able to add DVDs to their queue, and view their queue

Typically you'd have corresponding controllers for User, Queue and Dvd that provide CRUD actions mapped to standard routes, with views for the index, new & edit actions.

Mori
  • 27,279
  • 10
  • 68
  • 73
  • You need to add `has_many :dvd_queues` anywhere you wat to use `has_many X through: :dvd_queues`. Why not use has_and_belongs_to_many and eliminate the join model? – Peter Brown Jun 19 '12 at 01:24
  • thanks...and how does this tie into the views/controllers? which models need views and controllers if i want the user to be able to add DVDs to their queue, and view their queue – Matthew Berman Jun 19 '12 at 01:24