我有三个类别的用户,司机,公司。每个公司或司机都属于一个用户。这些模型看起来像
class Company < User
has_many :driver
end
class Driver < User
end
class User < ActiveRecord::Base
enum role: [:admin, :support, :B2B , :B2C]
end数据库看起来像这样
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :email
t.timestamps null: false
end
end
end
class CreateCompanies < ActiveRecord::Migration
def change
create_table :companies do |t|
t.string :comp_name
t.string :first_name_counterpart
t.string :last_name_counterpart
t.string :iban_nr
t.string :bic
t.string :email_counterpart
t.string :addresse
t.string :city
t.string :zip
t.references :user
t.timestamps null: false
end
end
end
class CreateDrivers < ActiveRecord::Migration
def change
create_table :drivers do |t|
t.string :first_name
t.string :last_name
t.date :birthday
t.integer :sex
t.integer :dpi
t.integer :score
t.references :user
t.timestamps null: false
end
end
end为什么我不能创建一个驱动实例。例如,如果我尝试d = Driver.new,我会得到一个user-instance。d = Driver.new => #<Driver id: nil, email: nil, created_at: nil, updated_at: nil>
发布于 2016-03-10 04:00:59
这就是Rails从模型类中猜测表名的方式。引用table_name的ActiveRecord docs
根据继承层次结构中的类的名称来猜测表名(强制小写),继承层次结构直接从继承而来因此,如果层次结构看起来像:
Reply < Message < ActiveRecord::Base,那么即使在Reply上调用时,也可以使用Message来猜测表名。
您应该能够通过table_name=设置器强制使用正确的表名,例如:
class Driver < User
self.table_name = "drivers"
end另一方面,我也不确定你的方法(通过这样的继承)不会在其他地方引起问题。
发布于 2016-03-10 04:24:30
如果你有像你一样继承的模型:
class User < ActiveRecord::Base
enum role: [:admin, :support, :B2B , :B2C]
end
class Company < User
has_many :driver
end
class Driver < User
endrails推断您正在寻找单表继承(STI),并期望只有一个基表users,该表具有列type,该列存储具有实际类名的User、Company和Driver的记录(例如:Company或Driver等)。
如果您更希望拥有单独的表users、companies和drivers,因为这些表中的每个表都有不同的列集,并且您将继承放在适当位置的唯一原因是为了共享一些公共功能,那么您应该将公共功能提取到modules中,并将它们混合到这些模型中(通过继承ActiveRecord::Base。
rails通过active_support提供了被称为concerns的东西,以将通用功能提取到模块中,并直观地混合它们。
有关更多信息,请参阅ActiveRecord::Inheritance和ActiveSupport::Concern。
https://stackoverflow.com/questions/35900858
复制相似问题