首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >类别has_many视频,视频belongs_to_many类别

类别has_many视频,视频belongs_to_many类别
EN

Stack Overflow用户
提问于 2016-10-22 01:13:24
回答 2查看 194关注 0票数 0

我正在做一个像9gagtv风格的小视频网站,网站中的视频有一个类别,所以用户可以找到所有的科技视频,例如,但一些视频belongs_to_many类别喜欢当一个视频是关于科技,但也是有趣的,所以它将显示在两个类别的视频,我不知道怎么做?在视频表中是否需要多个t.references?这段关系会怎样发展呢?

category.rb

代码语言:javascript
运行
复制
class Category < ApplicationRecord
has_many :videos
end

video.rb

代码语言:javascript
运行
复制
class Video < ApplicationRecord
belongs_to :category
end

类别迁移

代码语言:javascript
运行
复制
class CreateCategories < ActiveRecord::Migration[5.0]
def change
create_table :categories do |t|
    t.string :title
  t.timestamps
end
end
end

视频迁移

代码语言:javascript
运行
复制
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
EN

回答 2

Stack Overflow用户

发布于 2016-10-22 01:22:42

您可以使用has_and_belongs_to_many通过第三个表创建多对多关联。

型号:

代码语言:javascript
运行
复制
class Category < ApplicationRecord
  has_and_belongs_to_many :videos
end

class Video < ApplicationRecord
  has_and_belongs_to_many :categories
end

迁移:

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2016-10-22 01:24:32

我想你要找的是has_and_belongs_to_many关系(see more)

它应该看起来像这样

类别

代码语言:javascript
运行
复制
class Category < ApplicationRecord
  has_and_belongs_to_many:videos
end

视频

代码语言:javascript
运行
复制
class Video < ApplicationRecord
  belongs_to :category
end

和迁移

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40182152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档