简体   繁体   English

HABTM属性的setter上的alias_method_chain不起作用

[英]alias_method_chain on an HABTM attribute's setter isn't working

So I have a HABTM for both Posts and Topics. 所以我有一个用于帖子和主题的HABTM。 A Post HABTM Topics, and a Topic HABTM Posts. HABTM发布主题和HABTM发布主题。 What I need to do is call some method in conjunction with calling post.topics=() 我需要做的是结合调用post.topics=()来调用某些方法

This is what I've tried doing in Post.rb: 这是我尝试在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=() 但是,这现在破坏了post.topics=()

I won't get an error or anything, but topics() will still be the old value after changing it with topics=() 我不会收到任何错误或任何提示,但topics()在通过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. 如果我提出一个错误topics_with_extra_stuff= ,跟踪会说,有一个错误topics= ,所以我知道它变得在那里。 I also know that extra_stuff() was called. 我也知道extra_stuff()被调用了。

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. 它不应该再有2个主题,而只有1个。

Thanks for any insight. 感谢您的任何见解。

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. 我也遇到了同样的问题(Rails 2.3.11),但是对我来说,添加before_add回调不是一种选择,因此我一直在寻找。 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

我最终仅使用关联回调:before_add

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM