2014-01-16 54 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 
相关问题