在 Rails 上的 Ruby 上创建公告板
Create a bulletin board on Ruby on Rails
有必要写一个按类别划分广告的公告板(广告可以同时在不同类别中)。
广告必须有多种状态(审核/批准/拒绝),只有管理员可以更改状态。
告诉我需要在模型中为广告 table 和类别创建哪些字段?我该如何将它们联系在一起?
在此先感谢您的帮助。
# 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,到link这两个表。按照 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
有必要写一个按类别划分广告的公告板(广告可以同时在不同类别中)。 广告必须有多种状态(审核/批准/拒绝),只有管理员可以更改状态。
告诉我需要在模型中为广告 table 和类别创建哪些字段?我该如何将它们联系在一起?
在此先感谢您的帮助。
# 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,到link这两个表。按照 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