【问题标题】:Why does attr_accessor :type return nil?为什么 attr_accessor :type 返回 nil?
【发布时间】:2017-06-06 10:12:09
【问题描述】:

当覆盖我的一个类的to_s 方法时,我发现type 字段是nil。我很肯定它有一个非空值。我有一个遗留数据库,所以我使用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 可以正常工作。为什么会这样?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord accessor


    【解决方案1】:

    删除线

    attr_accessor :type
    

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

    幕后发生的事情是 attr_accessor 声明了两个虚拟方法:

    def type
      @type
    end
    
    def type=(value)
      @type = value
    end
    

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

    【讨论】:

    • 所以我不应该将attr_accesor 用于作为数据库列的字段?
    • 除非你想覆盖默认行为,否则你不应该这样做。
    猜你喜欢
    • 1970-01-01
    • 2014-11-11
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    相关资源
    最近更新 更多