gpt4 book ai didi

ruby-on-rails - 单表继承 Ruby on Rails 5.2

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:49 26 4
gpt4 key购买 nike

I have three models User, Individual and Business. I also created three tables one for each. My individual and user table are identical so i inherited from user.rb My problem was when i came to the business.rb, i was able to access all of the parent attributes of User (example: first_name) but i could not access the model specific attributes (example: company_name) which are in the businesses table.

class User < ApplicationRecord
# This is the user model
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
enum status: {unverified: 0, verified: 1}
end


# This is the business model
class Business < User
end
individual.rb
# # This is the individual model
class Individual < User
end
schema.rb
# This is the schema for all the models
ActiveRecord::Schema.define(version: 2018_06_09_091056) do
create_table "businesses", force: :cascade do |t|
t.string "company_address"
t.string "company_name"
t.string "company_phone_number"
t.text "documents"
end
create_table "individuals", force: :cascade do |t|
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.integer "status", default: 0
t.string "date_of_birth"
t.text "passport"
t.string "country"
t.string "personal_address"
t.text "recovery_photo"
t.string "type"
t.string "email", default: "", null: false
# etc..
end
end

最佳答案

之所以称为单表继承是因为:所有数据都存储在单个表中。

class Individual < User ,您正在将此模型的数据存储在 users 中表。

这些记录的唯一区别在于 individual.type == 'Individual' .

individualsbusinesses在您当前的设计中,表格从未使用过

话虽如此,下面是我将如何更改它:

class User < ApplicationRecord
# This is the user model
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
enum status: {unverified: 0, verified: 1}
end

# app/models/individual.rb
class Individual < User
end

# app/models/business.rb
class Business < User
has_one :business_attributes
end

# app/models/business_attributes.rb
class BusinessAttributes < ApplicationRecord
belongs_to :business
end

# db/schema.rb
ActiveRecord::Schema.define(version: 2018_06_09_091056) do
create_table "business_attributes", force: :cascade do |t|
t.string "company_address"
t.string "company_name"
t.string "company_phone_number"
t.text "documents"
end
create_table "users", force: :cascade do |t|
t.string "first_name"
t.string "last_name"
t.integer "status", default: 0
t.string "date_of_birth"
t.text "passport"
t.string "country"
t.string "personal_address"
t.text "recovery_photo"
t.string "type"
t.string "email", default: "", null: false
# etc..
end
end

关于ruby-on-rails - 单表继承 Ruby on Rails 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50773463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com