2016-10-21 6 views
0

私は9gagtvスタイル のような小さなビデオサイトのようにやっていて、サイト内のビデオにカテゴリがありますので、ユーザはすべてのTechビデオを見つけることができます。例えば ですが、ビデオはハイテクに関するものですが、面白いので、両方のカテゴリーのビデオにも表示されますが、どうすればよいか分かりません。 動画テーブルに複数のt.referencesが必要ですか?関係はどうやって行くの?カテゴリhas_manyビデオ、ビデオbelongs_to_manyカテゴリ

category.rb

class Category < ApplicationRecord 
has_many :videos 
end 

video.rb

class Video < ApplicationRecord 
belongs_to :category 
end 

カテゴリの移行

class CreateCategories < ActiveRecord::Migration[5.0] 
def change 
create_table :categories do |t| 
    t.string :title 
    t.timestamps 
end 
end 
end 

ビデオ移行

class CreateVideos < ActiveRecord::Migration[5.0] 
def change 
create_table :videos do |t| 
    t.string :url 
    t.string :title 
    t.text :description 
    t.integer :duration 
    t.references :category, foreign_key: true 
    t.timestamps 
    end 
end 
end 

答えて

1

has_and_belongs_to_many を使用すると、3番目のテーブルから多対多の関連付けを作成できます。

モデル:

class Category < ApplicationRecord 
    has_and_belongs_to_many :videos 
end 

class Video < ApplicationRecord 
    has_and_belongs_to_many :categories 
end 

移行:

class CreateCategories < ActiveRecord::Migration[5.0] 
    def change 
    create_table :categories do |t| 
     t.string :title 
     t.timestamps 
    end 
    end 
end 

class CreateVideos < ActiveRecord::Migration[5.0] 
    def change 
    create_table :videos do |t| 
     t.string :url 
     t.string :title 
     t.text :description 
     t.integer :duration 
     t.timestamps 
    end 
    end 
end 

class CreateCategoriesVideos < ActiveRecord::Migration[5.0] 
    def change 
    create_table :categories_videos do |t| 
     t.references :category, index: true 
     t.references :video, index: true 
    end 
    end 
end 
0

私はあなたが探しているものだと思うが、has_and_belongs_to_manyアソシエーション関係(see more

それはその

ようになっているはずです

カテゴリー

class Category < ApplicationRecord 
    has_and_belongs_to_many:videos 
end 

ビデオ

class Video < ApplicationRecord 
    belongs_to :category 
end 

と移行

class CreateCategoriesVideosJoinTable < ActiveRecord::Migration 
    def change 
    create_table :categories_videos, id: false do |t| 
     t.integer :category_id 
     t.integer :video_id 
    end 
    end 
end