简体   繁体   English

为什么attr_accessor:type返回nil?

[英]Why does attr_accessor :type return nil?

When overriding the to_s method of one of my classes, I'm getting that the field type is nil . 当重写我的一个类的to_s方法时,我得到的字段typenil I'm positive that it has a not null value. 我很肯定它具有不为null的值。 I have a legacy DB so I'm using self.inheritance_column = nil to tell rails not to look for inheritance. 我有一个遗留的数据库,所以我使用self.inheritance_column = nil告诉Rails不要寻找继承。 This is my class: 这是我的课:

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

Other fields, like genre do work properly. 其他领域(例如genre也可以正常工作。 Why does this happen? 为什么会这样?

Remove the line 删除线

attr_accessor :type

that basically overrides default Rails getter and setter for a field. 基本上会覆盖字段的默认Rails getter和setter。

What happens under the hood, is that attr_accessor declares two dummy methods: 实际情况是attr_accessor声明了两个虚拟方法:

def type
  @type
end

def type=(value)
  @type = value
end

Unless you have explicitly set the @type instance variable, it's value is nil since the explicit attr_accessor broke the magic that reads the value from the database field. 除非您显式设置了@type实例变量,否则其值为nil因为显式的attr_accessor打破了从数据库字段读取值的魔力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM