【问题标题】:Create a bulletin board on Ruby on Rails在 Ruby on Rails 上创建公告板
【发布时间】:2018-01-12 09:58:28
【问题描述】:

需要写一个布告栏,按类别划分广告(广告可以同时在不同的类别中)。 广告必须有多个状态(审核/批准/拒绝),只有管理员可以更改状态。

告诉我我需要为广告表格和类别创建模型中的哪些字段?以及如何将它们联系在一起?

提前感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby cancancan enumerize


    【解决方案1】:
    # app/models/advert.rb
    class Advert < ApplicationRecord
      has_and_belongs_to_many :categories
      enum status: [:moderation, :approved, :rejected]
    end
    
    # app/models/category.rb
    class Category < ApplicationRecord
      has_and_belongs_to_many :adverts
    end
    

    您需要有a JOINS table,才能链接这两个表。按照 Rails 约定,这将被称为adverts_categories(但如果愿意,它很容易覆盖)。

    例如,创建这些表的数据库迁移可以是:

    class CreateAdverts < ActiveRecord::Migration[5.0]
      def change
        create_table :adverts do |t|
          t.integer :status
          # ...
        end
      end
    end
    
    class CreateCategories < ActiveRecord::Migration[5.0]
      def change
        create_table :categories do |t|
          # (What fields does this table have?)
          t.string :name
          # ...
        end
      end
    end
    
    class CreateAdvertsCategories < ActiveRecord::Migration[5.0]
      def change
        create_join_table :adverts, :categories do |t|
          t.index :advert_id
          t.index :category_id
        end
      end
    end
    

    【讨论】:

    • StackOverflow 是英文网站;请尽量避免使用俄语! (不过,我通过翻译将您的评论...)
    • 对不起,汤姆。谢谢)声明表可以创建一个字段:category_id,并且对于Category字段:advert_id?我知道有必要创建 API 吗?
    • create_joins_table 将根据需要在 JOIN 表中创建 category_id 和 advert_id 列。因为是**has_and_**belongs_to_many 关联,所以adverts 表中没有category_id 字段。
    • 谢谢,汤姆)我会尝试实现它。
    • 至于 API... 我不知道你想构建什么。你的问题没有说。但很可能是的,您将需要某种 API。这将包括routes.rb、控制器操作和可能的视图/序列化器——取决于您想要实现的目标。我建议你通过 Rails 教程开始:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2016-06-18
    • 2012-07-22
    • 1970-01-01
    • 2011-10-26
    • 2011-04-10
    • 1970-01-01
    相关资源
    最近更新 更多