Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 为什么attr_访问器:type返回nil?_Ruby On Rails_Ruby_Activerecord_Accessor - Fatal编程技术网

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
?除非您希望覆盖默认行为,否则不应该这样做。