【问题标题】:NoMethodError: private method `y' in ActiveRecord when accessing an attributeNoMethodError:访问属性时 ActiveRecord 中的私有方法“y”
【发布时间】:2020-03-04 12:04:15
【问题描述】:

我有一个模型画板和一个模型组,它通过一个名为 ArtboardsGroups 的表具有多对多关系,该表具有与关系相关的 x 和 y 值的属性

class Artboard < ApplicationRecord
  has_many :artboards_groups, dependent: :destroy
  has_many :groups, -> { select("groups.id as id, groups.name as name, artboards_groups.x as x, artboards_groups.y as y, artboards_groups.index as index, artboards_groups.r as r") }, through: :artboards_groups
end

class ArtboardsGroup < ApplicationRecord
  belongs_to :artboard
  belongs_to :group
end

class Group < ApplicationRecord
  has_many :artboards_groups, dependent: :destroy
  has_many :artboards, through: :artboards_group
end

当我尝试自行访问该模型时,它工作得非常好,但是当我尝试通过画板选择组并访问“y”属性时,我收到一个错误,指出它是一个私有方法

NoMethodError: private method `y' called for #<Group id: 5, name: nil>

根据thread(10 多年前),这是因为在 ActiveRecord::Base 中有一个名为 'y' /lib/ruby/2.5.0/psych 的私有方法/y.rb 来自名为 psych 的 gem,它是一个 yaml 解析器

我不想更改 'y' 的属性名称,因为它引用了一个坐标系,并且 (x,y) 是坐标的标准。有没有其他方法可以解决这个问题?

【问题讨论】:

  • 如果您改为调用send(:y).y 会发生什么?
  • 您可以配置您的 Group 模型以将 y 方法委托给它关联的 ArtboardsGroup apidock.com/rails/Module/delegate
  • 据我所知,它实际上并不是来自 ActiveRecord。试试Group.new.method(:y).source_location。我收到["/Users/max/.rbenv/versions/2.6.3/lib/ruby/2.6.0/psych/y.rb", 5]
  • @arieljuod 我得到一个 NoMethodError: undefined method `end_line=' for nil:NilClass
  • @max 你说得对,我对操作进行了编辑

标签: ruby-on-rails ruby activerecord activemodel


【解决方案1】:
class Group < ApplicationRecord
  undef :y
  has_many :artboards_groups, dependent: :destroy
  has_many :artboards, through: :artboards_group
end
irb(main):001:0> g = Group.new(y: 1, x: 2)
=> #<Group id: nil, x: 2.0, y: 1.0, created_at: nil, updated_at: nil>
irb(main):002:0> g.y
=> 1.0

:y 方法很可能来自 yaml 解析器 psych which monkeypatches it into the Kernel class

【讨论】:

  • 我还没有对此进行任何更广泛的测试,但我怀疑 ActiveRecord 在内部某处使用y
猜你喜欢
  • 1970-01-01
  • 2023-03-07
  • 2016-12-14
  • 2014-11-21
  • 2018-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-28
相关资源
最近更新 更多