NoMethodError:访问属性时,ActiveRecord中的私有方法“ y”

我有一个模型Artboard和一个模型组,该模型通过称为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的Yaml解析器

我不想更改“ y”的属性名称,因为它引用的是坐标系,而(x,y)是坐标的标准。还有其他方法可以解决吗?

jackychen0116 回答:NoMethodError:访问属性时,ActiveRecord中的私有方法“ y”

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解析器心理which monkeypatches it into the Kernel class

本文链接:https://www.f2er.com/3141713.html

大家都在问