ruby-on-rails - 需要从另一个表添加列
问题描述
我有两个模型:Account
和Profile
. 在Account
我有role
专栏。我需要在表中添加role
列profiles
。
我包括在Profile
has_one :account
关联和模型belongs_to :profile
中。Account
我认为解决方案就在附近。
配置文件.rb
class Profile < ApplicationRecord
has_one :account
end
帐号.rb
class Account < ApplicationRecord
devise :registerable, :database_authenticatable, :rememberable,
:trackable, :confirmable, :lockable, :recoverable, :validatable
belongs_to :profile, foreign_key: 'profile_id'
enum role: %i[user admin]
end
架构.rb
create_table "accounts", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.string "remember_token"
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"
t.string "confirmation_token"
t.datetime "confirmed_at"
t.datetime "confirmation_sent_at"
t.string "unconfirmed_email"
t.integer "failed_attempts", default: 0, null: false
t.string "unlock_token"
t.datetime "locked_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "profile_id", null: false
t.integer "role", default: 0
t.index ["profile_id"], name: "index_accounts_on_profile_id"
end
create_table "profiles", force: :cascade do |t|
t.string "last_name", null: false
t.string "first_name", null: false
t.string "middle_name"
t.string "email", null: false
t.text "about"
t.date "hire_date", null: false
end
我想将profiles
表中的哪个添加到列中Account.role
。
解决方案
如何仅使用访问role
数据的函数accounts
class Profile < ApplicationRecord
def role
return account.role unless account.nil?
end
end