【发布时间】:2018-01-12 09:58:28
【问题描述】:
需要写一个布告栏,按类别划分广告(广告可以同时在不同的类别中)。 广告必须有多个状态(审核/批准/拒绝),只有管理员可以更改状态。
告诉我我需要为广告表格和类别创建模型中的哪些字段?以及如何将它们联系在一起?
提前感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails ruby cancancan enumerize
需要写一个布告栏,按类别划分广告(广告可以同时在不同的类别中)。 广告必须有多个状态(审核/批准/拒绝),只有管理员可以更改状态。
告诉我我需要为广告表格和类别创建模型中的哪些字段?以及如何将它们联系在一起?
提前感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails ruby cancancan enumerize
# 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
【讨论】:
create_joins_table 将根据需要在 JOIN 表中创建 category_id 和 advert_id 列。因为是**has_and_**belongs_to_many 关联,所以adverts 表中没有category_id 字段。
routes.rb、控制器操作和可能的视图/序列化器——取决于您想要实现的目标。我建议你通过 Rails 教程开始:)