Dav*_*vid 1 ruby activerecord ruby-on-rails activemodel
我有一个模型画板和一个模型组,它们通过名为 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
Run Code Online (Sandbox Code Playgroud)
当我尝试单独访问它时,该模型工作得很好,但是当我尝试通过画板选择组并访问“y”属性时,我收到一个错误,它是私有方法
NoMethodError: private method `y' called for #<Group id: 5, name: nil>
Run Code Online (Sandbox Code Playgroud)
根据这个线程(10多年前),这是因为ActiveRecord::Base 中有一个名为 'y' /lib/ruby/2.5.0/psych/y.rb 的私有方法,它来自一个名为psych的gem是一个 yaml 解析器
我不想更改“y”的属性名称,因为它引用坐标系并且 (x,y) 是坐标标准。还有其他方法可以解决这个问题吗?
class Group < ApplicationRecord
undef :y
has_many :artboards_groups, dependent: :destroy
has_many :artboards, through: :artboards_group
end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
该:y方法很可能来自 yaml 解析器 psych ,它将它猴子补丁到 Kernel 类中。
| 归档时间: |
|
| 查看次数: |
478 次 |
| 最近记录: |