ruby-on-rails Rails 7.1中的别名关联

xxe27gdn  于 4个月前  发布在  Ruby
关注(0)|答案(1)|浏览(63)

在奥登时代,我可以这样做:

class Thing < ApplicationRecord
  belongs_to :thing_member

  alias_attribute :member, :thing_member
end

Thing.new(thing_member: blah) => success!
Thing.new(member: blah) => also success!

字符串
在Rails 7.1中,我们现在得到一个弃用警告,说.member不是一个true属性,我们应该停止使用alias_attribute,而使用alias_method。很好,但是遵循这个建议会破坏一些东西:

class Thing < ApplicationRecord
  belongs_to :thing_member

  alias_method :member, :thing_member
end

Thing.new(thing_member: blah) => success!
Thing.new(member: blah) => NoMethodError: undefined method `member='


定义两次关联是有效的,但感觉很恶心:

class Thing < ApplicationRecord
  belongs_to :thing_member
  belongs_to :member, class_name: "ThingMember", foreign_key: "thing_member_id"
end

Thing.new(thing_member: blah) => success!
Thing.new(member: blah) => Pyrrhic victory :(


有没有更好的、规范的方法来实现这一点?这只是一个需要避免的坏习惯吗?这种情况下是否应该有一个alias_association宏?

bihw5rsg

bihw5rsg1#

我可能只是添加我自己的alias_association,它既做了getter又做了setter。

相关问题