HABTM 属性设置器上的 alias_method_chain 不起作用

发布于 2024-11-16 08:42:04 字数 925 浏览 11 评论 0原文

所以我有一个用于帖子和主题的 HABTM。一个帖子 HABTM 主题,一个主题 HABTM 帖子。我需要做的是调用一些方法并调用 post.topics=()

这是我在 Post.rb 中尝试做的事情:

def topics_with_extra_stuff=(topics)
  topics_without_extra_stuff=(topics)
  extra_stuff()
end
alias_method_chain :topics=, :extra_stuff

但是,这现在破坏了 post.topics =()

我不会收到错误或任何错误,但使用 topics=() 更改后 topics() 仍将是旧值

如果我提出一个错误topics_with_extra_stuff=,跟踪会说 topics= 中存在错误,所以我知道它正在进入那里。我还知道调用了 extra_stuff()

这是输出的示例:

>> p = Post.last
=> #<Post id:1 ....>
>> p.topics
=> [#<Topic id:1 ....>, #<Topic id:2 ....>]
>> p.topics = [ p.topics.first ]
=> [#<Topic id:1 ....>]
>> p.topics
=> [#<Topic id:1 ....>, #<Topic id:2 ....>]

它不应该仍然有 2 个主题,而只有 1 个

。感谢您的见解。

So I have a HABTM for both Posts and Topics. A Post HABTM Topics, and a Topic HABTM Posts. What I need to do is call some method in conjunction with calling post.topics=()

This is what I've tried doing in Post.rb:

def topics_with_extra_stuff=(topics)
  topics_without_extra_stuff=(topics)
  extra_stuff()
end
alias_method_chain :topics=, :extra_stuff

However, this now breaks post.topics=()

I won't get an error or anything, but topics() will still be the old value after changing it with topics=()

If I raise an error in topics_with_extra_stuff=, the trace will say that there was an error in topics=, so I know it's getting in there. I also know that extra_stuff() was called.

Here's an example of the output:

>> p = Post.last
=> #<Post id:1 ....>
>> p.topics
=> [#<Topic id:1 ....>, #<Topic id:2 ....>]
>> p.topics = [ p.topics.first ]
=> [#<Topic id:1 ....>]
>> p.topics
=> [#<Topic id:1 ....>, #<Topic id:2 ....>]

It shouldn't still have 2 Topics, just 1.

Thanks for any insight.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

若水微香 2024-11-23 08:42:04

我遇到了同样的问题(Rails 2.3.11),但是添加 before_add 回调对我来说不是一个选择,所以我一直在寻找。最后,我设法使用这种替代的别名方式使其工作:

old_workflows_setter = self.instance_method(:workflows=)

define_method :workflows= do |value|
  # my code
  old_workflows_setter.bind(self).call(value)
end

I had this same problem (Rails 2.3.11), but adding a before_add callback was not an option for me so I kept looking. Finally I managed to make it work using this alternative way of aliasing:

old_workflows_setter = self.instance_method(:workflows=)

define_method :workflows= do |value|
  # my code
  old_workflows_setter.bind(self).call(value)
end
被翻牌 2024-11-23 08:42:04

我最终只是使用关联回调 :before_add 来代替。

I ended up just using the association callback :before_add instead.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文