为什么attr_accessor:type return nil?

时间:2017-06-06 10:12:09

标签: ruby-on-rails ruby activerecord accessor

当覆盖其中一个课程的to_s方法时,我认为字段typenil。我肯定它有一个非空值。我有一个遗留数据库,因此我使用self.inheritance_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

其他字段(例如genre)可以正常运行。为什么会这样?

1 个答案:

答案 0 :(得分:2)

删除行

attr_accessor :type

基本上覆盖字段的默认Rails getter和setter。

引发的是attr_accessor声明了两种虚拟方法:

def type
  @type
end

def type=(value)
  @type = value
end

除非您已明确设置@type实例变量,否则其值为nil,因为显式attr_accessor打破了从数据库字段读取值的魔力。

相关问题