tet5uo
tet5uo

Reputation: 139

Rails model has_many :items twice

user.rb

class User < ActiveRecord::Base
   has_many :videos
end

video.rb

class Video < ActiveRecord::Base
    belongs_to :user
end

I want users to be able to add videos to their 'collection' that don't belongs_to them (were not uploaded by them).

I guess I will need a many to many relationship so I have considered a has_many through a 'collection' join model. I don't understand how I would then differentiate between uploaded and collected videos.

I have also considered two new models a 'collection' model that belongs_to :user and has_many :videos through a 'collected_videos' join model.

Is there a better way to go around implementing this? Sorry if my question is not clear, new to StackOverflow and development in general. Thanks

Upvotes: 0

Views: 89

Answers (1)

Joel Brewer
Joel Brewer

Reputation: 1652

If I understand what you are asking correctly, I think you can set things up something like this to achieve what you want:

class User
  has_and_belongs_to_many :videos
end

class Video
  has_and_belongs_to_many :users
  belongs_to :owner, class_name: "User"
end

Take a closer look at the documentation for has_and_belongs_to_many: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association

Upvotes: 2

Related Questions