2015-11-03 74 views
2

我從Ruby on Rails入手,遇到一些困難。Ruby on Rails has_many relation

爲了說明一下上下文,我想要做的是一個應用程序,用戶可以創建帳戶,每個帳戶都有一個頻道,每個頻道都有一定數量的視頻。

此外,還有一個時間表,每個視頻可以添加視頻。所以時間表也有很多視頻。

現在我有以下型號:

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 

我怎樣才能建立一個關係,其中一個視頻可以屬於在同一時間,以引導和屬於時間線?

我覺得做的最好的方式,是有名稱的新表像timelinerelation與領域ID_TIMELINEID_VIDEO和例如用於時間表我有視頻2,3,4和時間表2我有視頻3,4,5。

所以該表將有:

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

的事情是,我不知道如何做到這一點的Ruby on Rails的。

+0

http://guides.rubyonrails.org/association_basics.html#the-has-many通過協會 – AbM

+0

@AbM基本上我應該生成一個新的腳手架,將他們兩個?我正在考慮這個問題,但我不確定。然後我編寫類似於「相應的遷移可能如下所示」的遷移,然後使用rake db:migrate? – heisenberg

+0

@AbM ha好,謝謝:) – heisenberg

回答

1

根據您提供的示例,我看到視頻可以屬於多個時間軸。如果是這樣,你需要建立一個多對多的關係,如綱要here

在你的情況,你可以創建一個連接模型,說TimelineRelation運行:

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 
1

你不需要額外的表格。只需將視頻模型添加字段timeline_id並添加另一個belongs_to關係

+0

我相信@heisenberg正在尋找的是多對多的關係。在他給出的例子中,視頻3屬於時間軸1和時間軸2 – AbM