扶手:覆盖的ActiveRecord联想法 [英] Rails: Overriding ActiveRecord association method
问题描述
有没有办法覆盖由一个ActiveRecord协会提供的方法之一?
Is there a way to override one of the methods provided by an ActiveRecord association?
比方说我有以下典型的多态的has_many:通过关联:
Say for example I have the following typical polymorphic 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
正如你可能知道这增加了相关方法像标签,标签和其中的故事模型整体转换;&LT;,标签=,tags.empty?等等。
As you probably know this adds a whole slew of associated methods to the Story model like tags, tags<<, tags=, tags.empty?, etc.
我如何去重写这些方法之一?具体的标签&LT;&LT;方法。这是pretty的容易覆盖一个普通的类方法,但我似乎无法找到如何覆盖关联方法的任何信息。做这样的事情
How do I go about overriding one of these methods? Specifically the tags<< method. It's pretty easy to override a normal class methods but I can't seem to find any information on how to override association methods. Doing something like
def tags<< *new_tags
#do stuff
end
产生一个语法错误,当它被称为所以它显然不是那么简单。
produces a syntax error when it's called so it's obviously not that simple.
推荐答案
您可以使用的has_many
块与方法扩展您的关联。见注释使用块来扩展你的联想<一href="http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many#461-User-a-block-to-extend-your-associations">here.
覆盖现有的方法也适用,不知道它是否是一个好主意,但是。
You can use block with has_many
to extend your association with methods. See comment "Use a block to extend your associations" here.
Overriding existing methods also works, don't know whether it is a good idea however.
has_many :tags, :through => :taggings, :order => :name do
def << (value)
"overriden" #your code here
super value
end
end
这篇关于扶手:覆盖的ActiveRecord联想法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!