新手问题 Active Record 字段 type 的含义?

ly7524126 · June 21, 2017 · Last by tangmonk replied at June 25, 2017 · 2149 hits

order 表里面有个 type 字段默认值 OrderType

Order.first.class
 OrderType

取出来的类型是 OrderType 有没有什么方法能让取出来的类型还是 Order

type 是关键字,尽量避免使用

定义字段的时候 type 是关键字 还能抢救吗

Reply to ly7524126

写 migration 吧😋

Reply to winse

好吧 我再去找找看有没有什么方法能实现的 不行在 migration

去看一下 becomes 和 becomes! 方法

class AAddress < Address

end

class BAddress < Address

end

a_address = Address.new(type: 'AAddress')
puts a_address.class.name  
结果 'AAddress'

puts a_address.becomes(Address).class.name
结果 'Address'

type 是 ActiveRecord 的单表继承默认关键字,可以改成别的,这样 type 字段就可以用了

class Order < ActiveRecord::Base
  self.inheritance_column = "_type"
end

type 字段是可以用来实现继承 Model 的哦

例如 User, Group 都是同一个表 users

Reply to dontyang

好的谢谢 我去试试👍 👍

Reply to numbcoder

查资料的时候看到过这种写法 去试试 谢谢

Reply to huacnlee

继承关系 好的 谢谢

关键字:Single Table Inheritance

You need to Sign in before reply, if you don't have an account, please Sign up first.