【发布时间】:2015-03-18 11:15:14
【问题描述】:
我需要知道,是否有办法在 Rails 中使用单一模型处理不同类型的用户/客户端。
我真正需要做什么? - 我需要在我的数据库中保存不同类型的客户端。所以,我有这个迁移:
class CreateClients < ActiveRecord::Migration
def change
create_table :clients do |t|
t.string :name # Person name if "Personal", Company name if type "Company"
t.string :nif # fillable only if type is Company
t.string :identity_card_number # fillable only if type is Personal
t.integer :client_type # Type can be Personal or Company
t.references :company, index: true # if type is personal, it can belong to a company
t.timestamps null: false
end
end
end
然后我创建这个模型
class Client < ActiveRecord::Base
has_many :employees, class_name: 'Client', foreign_key: 'company_id'
belongs_to :company, class_name: 'Client'
end
注意:个人帐户可以属于或不属于公司。
根据您的经验,我这样做的方式是否正确?还有其他方法吗?
编辑:
嗨@manfergo25,
对此我还有一个问题。 “公司”和“个人”都是“客户账户”,这样,两者都必须能够购买服务。
如果我需要将客户与服务相关联,我可以这样做吗?
class Personal < Account
has_many :services
end
和
class Service < ...
belongs_to :account
end
??
【问题讨论】:
-
你可以使用
STI(Single Table Inheritance),比如class User < ActiveRecord::Base,那么用户可以是class PersonalUser < User或者class CompanyUser < User
标签: ruby-on-rails ruby ruby-on-rails-4 associations