【问题标题】:Category has_many videos, video belongs_to_many categories类别 has_many 个视频,视频属于_to_many 个类别
【发布时间】:2016-10-21 17:13:23
【问题描述】:

我正在做一个像 9gagtv 风格的小视频网站 并且网站中的视频有一个类别,因此用户可以找到所有的技术视频,例如 但是有些视频属于_to_many 类别,例如当视频是关于技术的但也很有趣,所以它会出现在这两个类别的视频中,我不知道该怎么做? 在视频表中需要多个 t.references 吗?感情会怎样?

category.rb

class Category < ApplicationRecord
has_many :videos
end

视频.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

【问题讨论】:

    标签: ruby-on-rails model-associations


    【解决方案1】:

    您可以使用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
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-16
        • 1970-01-01
        • 1970-01-01
        • 2015-06-27
        • 2014-06-18
        • 2014-02-10
        • 1970-01-01
        • 2020-11-22
        相关资源
        最近更新 更多