定义STI表的关联



我有一个表User,有三个表继承自这个表:

class Manager < User
has_many :projects
end
class Qa < User
has_many :bugs
end
class Developer < User
has_many :bugs
has_and_belongs_to_many :projects
end

projectbug表如下:

class Bug < ApplicationRecord
belongs_to :developer
belongs_to :qa
belongs_to :project
end
class Project < ApplicationRecord
belongs_to :manager
has_many :bugs
has_and_belongs_to_many :developers
end

User表存在于数据库中,我正在为Manager, QA和Developer使用STI,但是我如何定义与这三个表的关联对应的迁移?

所以,我最终使用STI。数据库迁移如下:

class DeviseCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
## Database authenticatable
t.string :email,              null: false, default: ''
t.string :encrypted_password, null: false, default: ''
## Recoverable
t.string   :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
# t.integer  :sign_in_count, default: 0, null: false
# t.datetime :current_sign_in_at
# t.datetime :last_sign_in_at
# t.inet     :current_sign_in_ip
# t.inet     :last_sign_in_ip
## Confirmable
# t.string   :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string   :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string   :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.string :type, default: 'Developer'
t.string :name
t.timestamps null: false
end
add_index :users, :email,                unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token,   unique: true
# add_index :users, :unlock_token,         unique: true
end
end
class CreateBugs < ActiveRecord::Migration[5.2]
def change
create_table :bugs do |t|
t.string :title
t.datetime :deadline
t.string :kind
t.string :stature
t.text :description
t.belongs_to :developer, index: false, null: true, default: nil
t.belongs_to :qa, index: true
t.belongs_to :project, index: true
t.timestamps
end
end
end
class CreateDevelopersProjects < ActiveRecord::Migration[5.2]
def change
create_table :projects do |t|
t.string :name
t.belongs_to :manager, index: true
t.timestamps
end
create_table :projects_users, id: false do |t|
t.belongs_to :developer, index: true
t.belongs_to :project, index: true
t.timestamps
end
add_index :projects, :name, unique: true
end
end

相关内容

  • 没有找到相关文章

最新更新