我正在做一个像9gagtv风格的小视频网站,网站中的视频有一个类别,所以用户可以找到所有的科技视频,例如,但一些视频belongs_to_many类别喜欢当一个视频是关于科技,但也是有趣的,所以它将显示在两个类别的视频,我不知道怎么做?在视频表中是否需要多个t.references?这段关系会怎样发展呢?
category.rb
class Category < ApplicationRecord
has_many :videos
endvideo.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发布于 2016-10-22 01:22:42
您可以使用has_and_belongs_to_many通过第三个表创建多对多关联。
型号:
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发布于 2016-10-22 01:24:32
我想你要找的是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
endhttps://stackoverflow.com/questions/40182152
复制相似问题