Ruby on rails 为什么attr_访问器:type返回nil?
当重写我的一个类的Ruby on rails 为什么attr_访问器:type返回nil?,ruby-on-rails,ruby,activerecord,accessor,Ruby On Rails,Ruby,Activerecord,Accessor,当重写我的一个类的to_s方法时,我得到的字段type是nil。我肯定它有一个非空值。我有一个遗留数据库,所以我使用self.heritation\u column=nil告诉rails不要寻找继承。这是我的班级: class BookEntry < ApplicationRecord self.inheritance_column = nil attr_accessor :type self.table_name = 'bookEntries' has_many :use
to_s
方法时,我得到的字段type
是nil
。我肯定它有一个非空值。我有一个遗留数据库,所以我使用self.heritation\u column=nil
告诉rails不要寻找继承。这是我的班级:
class BookEntry < ApplicationRecord
self.inheritance_column = nil
attr_accessor :type
self.table_name = 'bookEntries'
has_many :users_payout_methods, class_name: 'UsersBooks', primary_key: 'id', foreign_key: 'bookId_fk'
has_many :users, :through => :users_payout_methods
def to_s
"type: "+ type + ", genre:" + genre
end
end
class BookEntry:用户\u支付\u方法
def至美国
类型:“+类型+”,类型:“+类型
结束
结束
其他字段,如genre
可以正常工作。为什么会发生这种情况?删除该行
attr_accessor :type
这基本上覆盖了字段的默认Rails getter和setter
在引擎盖下发生的是attr_accessor
声明了两个虚拟方法:
def type
@type
end
def type=(value)
@type = value
end
除非您显式设置了@type
实例变量,否则它的值是nil
,因为显式attr\u访问器打破了从数据库字段读取值的魔法。删除该行
attr_accessor :type
这基本上覆盖了字段的默认Rails getter和setter
在引擎盖下发生的是attr_accessor
声明了两个虚拟方法:
def type
@type
end
def type=(value)
@type = value
end
除非已显式设置@type
实例变量,它的值是nil
,因为显式的attr\u访问器
打破了从数据库字段读取值的魔法。所以我不应该对DB列字段使用attr\u访问器
?除非您想覆盖默认行为,您不应该这样做。因此,我不应该对DB列字段使用attr\u accesor
?除非您希望覆盖默认行为,否则不应该这样做。