有沒有辦法重寫ActiveRecord關聯提供的方法之一?Rails:重寫ActiveRecord關聯方法
例如說我有以下典型的多態的has_many:通過關聯:
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
正如你可能知道,這增加的相關方法,以類似標籤的故事模型整體轉換,標籤< <,標籤= ,tags.empty?等。
我該如何去重寫這些方法之一?具體是標籤< <方法。重寫一個普通的類方法是很容易的,但我似乎無法找到關於如何重載關聯方法的任何信息。做類似
def tags<< *new_tags
#do stuff
end
當它被調用時會產生語法錯誤,所以它顯然不那麼簡單。
你在做什麼?這可能最終會打破其他ActiveRecord功能,並且可能有更好的方法來做你正在嘗試的東西 – Gareth 2010-05-23 07:19:54