Ruby on rails HABTM属性上的别名"方法"链';s setter不是';行不通

Ruby on rails HABTM属性上的别名"方法"链';s setter不是';行不通,ruby-on-rails,overriding,has-and-belongs-to-many,setter,alias-method-chain,Ruby On Rails,Overriding,Has And Belongs To Many,Setter,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=

因此,我有一个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\u中用_extra\u 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 ....>]
>p=Post.last
=> #
>>p.主题
=> [#, #]
>>p.topics=[p.topics.first]
=> [#]
>>p.主题
=> [#, #]
它不应该还有两个主题,只有一个


感谢您的帮助。

我最终只使用了关联回调
:在添加
之前。

我也遇到了同样的问题(Rails 2.3.11),但在添加
之前添加
回调对我来说不是一个选项,所以我一直在寻找。最后,我使用这种别名的替代方法成功地实现了这一点:

old_workflows_setter = self.instance_method(:workflows=)

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

从Rails3.2开始,我认为您不需要这样做——关联访问器是在类中包含的模块中创建的,因此您应该能够重新定义并调用super()