有没有办法覆盖 ActiveRecord 关联提供的方法之一?
例如,我有以下典型的多态 has_many :through association:
class Story < ActiveRecord::Base
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings, :order => :name
end
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :stories, :through => :taggings, :source => :taggable, :source_type => "Story"
end
您可能知道,这会向 Story 模型添加一大堆关联方法,例如标签、标签<<、标签=、标签.empty? 等。
我如何着手覆盖这些方法之一?特别是 tags<< 方法。覆盖普通类方法非常容易,但我似乎找不到有关如何覆盖关联方法的任何信息。做类似的事情
def tags<< *new_tags
#do stuff
end
调用时出现语法错误,显然没那么简单。
最佳答案
您可以使用带有 has_many
的 block 来扩展您与方法的关联。请参阅评论“使用 block 来扩展您的关联”here .
覆盖现有方法也可以,但不知道这是否是个好主意。
has_many :tags, :through => :taggings, :order => :name do
def << (value)
"overriden" #your code here
super value
end
end
关于ruby-on-rails - rails : Overriding ActiveRecord association method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890761/