HABTM 属性设置器上的 alias_method_chain 不起作用
所以我有一个用于帖子和主题的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我遇到了同样的问题(Rails 2.3.11),但是添加
before_add
回调对我来说不是一个选择,所以我一直在寻找。最后,我设法使用这种替代的别名方式使其工作: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:我最终只是使用关联回调
:before_add
来代替。I ended up just using the association callback
:before_add
instead.