heisenberg
heisenberg

Reputation: 1312

Ruby on Rails has_many relation

I am starting with Ruby on Rails and I am having a few difficulties.

To give a bit of context what I am trying to do is an app where users can create accounts, each account has one channel and each channel has an amount of videos.

Also there is a timelines which every video can add videos to. So timelines also has many videos.

By now I have the following models:

class Channel < ActiveRecord::Base
  belongs_to :member
  has_many :videos
end

class Member < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :channel
  has_many :timelines
end

class Video < ActiveRecord::Base
  belongs_to :channel
end

class Timeline < ActiveRecord::Base
  belongs_to :member
  has_many :videos
end

How can I build an relation where a video can belong to channel and at the same time belong to timeline?

I think the best way to do it is to have a new table with name like timelinerelation with fields ID_TIMELINE, ID_VIDEO and for instance for timeline one I have videos 2,3,4 and for timeline 2 I have videos 3,4,5.

So the table would have:

1 2;
1 3;
1 4;
2 3;
2 4;
2 5;

The thing is, I have no idea how to do this in ruby on rails.

Upvotes: 2

Views: 94

Answers (2)

AbM
AbM

Reputation: 7779

Following the example you provided, I see that a video can belong to multiple timelines. If so, you need to set up a many to many relationship as outline here.

In your case, you can create a join model, say TimelineRelation by running:

rails g model TimelineRelation timeline:references video:references

class Video < ActiveRecord::Base
  belongs_to :channel
  has_many :timeline_relations
  has_many :timelines, through: timeline_relations
end

class Timeline < ActiveRecord::Base
  belongs_to :member
  has_many :timeline_relations
  has_many :videos, through: timeline_relations
end

class TimelineRelation < ActiveRecord::Base
  belongs_to :timeline
  belongs_to :video
end

Upvotes: 1

Maciek Kocyła
Maciek Kocyła

Reputation: 71

You do not need extra table. Simply add field timeline_id to video model and add another belongs_to relation

Upvotes: 1

Related Questions