为什么attr_accessor:type返回nil?

问题描述:

当重写我的某个课程的to_s方法时,我得到的字段typenil。我肯定它有一个非空值。我有一个遗留数据库,所以我使用self.inheritance_column = nil来告诉轨道不寻找继承。这是我的班级:为什么attr_accessor:type返回nil?

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 

其他字段,如genre可以正常工作。为什么会发生?

删除线

attr_accessor :type 

,基本上覆盖默认Rails的getter和setter的领域。

引擎盖下会发生什么,是attr_accessor声明了两个虚拟方法:

def type 
    @type 
end 

def type=(value) 
    @type = value 
end 

除非你明确地设置@type实例变量,它的值是nil因为明确attr_accessor打破了读取值的魔法来自数据库字段。

+0

所以我不应该使用'attr_accesor'作为数据库列的字段? – garci560

+1

除非你想重写默认行为,否则你不应该这样做。 – mudasobwa