2014-01-16 53 views
1

我試圖創建一個Web應用程序來組織用戶的電視興趣,爲此,我需要存儲三種類型的數據:Shows,SeasonsEpisodes什麼是建立這種關係的有效方式?

我想查詢我的數據是這樣的:Show.find(1).season(2).episode.each。這應該返回每個節目的第二季節與id 1.我如何設置我的模型達到這個目的?

我試過在episodes具有season_idshow_id值,但它無法找到episodes屬於每個season

回答

1

也許這是一個好主意,通讀guides。假設你的實體關係看起來像這樣:

erd

你可以很容易地activerecord實現這個。該模型是這樣的:

require 'active_record' 

class Show < ActiveRecord::Base 
    has_many :seasons 
end 

class Season < ActiveRecord::Base 
    belongs_to :show 
    has_many :episodes 
end 

class Episode < ActiveRecord::Base 
    belongs_to :season 
end 

您的遷移可能會是這樣的:

require 'active_record' 

class CreateShows < ActiveRecord::Migration 
    def change 
     create_table :shows do |t| 
      t.timestamps 
     end 
    end 
end 

class CreateSeasons < ActiveRecord::Migration 
    def change 
     create_table :seasons do |t| 
      t.references :show, :null => false 
      t.timestamps 
     end 
    end 
end 

class CreateEpisodes < ActiveRecord::Migration 
    def change 
     create_table :episodes do |t| 
      t.references :season, :null => false 
      t.timestamps 
     end 
    end 
end 

把一些數據到數據庫中,並與它們進行查詢:

Show.find(1).seasons.first.episodes.each{ |e| puts e.title } 
+0

在遷移中,如果我把「t.references:season」等等。 ,我是否還需要爲季節和劇集提供'season_id'和'show_id'等數據。 – kitkat

+0

不,因爲't.references'會導致'id'屬性(外鍵)。 – Robin

1

在模式定義的關係,

Show 
has_many :seasons 

Season 
has_many :episodes 
belongs_to :show 

Episode 
belongs_to :season 

T你可以這樣打電話,

Show.find(1).seasons.first.episodes.each {} 
1

上面的答案很棒;我會採取這一步,使用的has_many的:通過在顯示模式選項和HAS_ONE:通過在情節模式:

# Show 

has_many :seasons 
has_many :episodes, through: :seasons 

# Season 

belongs_to :show 
has_many :episodes 

# Episode 

belongs_to :season 
has_one :show, through: :season 

這可以讓你做出這樣的電話:

Show.first.episodes 
Episode.first.show 

...並且還允許您編寫一些查詢最小化範圍,並編寫簡化查找相關信息的委託方法。

# Episode 
delegate :name, to: :show, prefix: :show 

Episode.first.show_name # => Episode.first.show.name 
相關問題