Rails:覆盖ActiveRecord关联方法

sea*_*ugh 34 ruby activerecord overriding ruby-on-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
Run Code Online (Sandbox Code Playgroud)

您可能知道这会为Story模型添加一大堆相关方法,如标签,标签<<,tags =,tags.empty?等.

我如何重写这些方法之一?特别是标签<<方法.覆盖普通的类方法很容易,但我似乎无法找到有关如何覆盖关联方法的任何信息.做点什么

def tags<< *new_tags
    #do stuff
end
Run Code Online (Sandbox Code Playgroud)

调用它时会产生语法错误,所以显然不那么简单.

Voy*_*yta 55

您可以使用块has_many来扩展与方法的关联.请在此处注释"使用块来扩展关联" .
覆盖现有方法也有效,但不知道这是否是一个好主意.

  has_many :tags, :through => :taggings, :order => :name do
    def << (value)
      "overriden" #your code here
      super value
    end     
  end
Run Code Online (Sandbox Code Playgroud)

  • 如何以这种方式覆盖关联getter? (3认同)

Pau*_*ver 18

如果您想在Rails 3.2中访问模型本身,您应该使用 proxy_association.owner

例:

class Author < ActiveRecord::Base
  has_many :books do
    def << (book)
      proxy_association.owner.add_book(book)
    end
  end

  def add_book (book)
    # do your thing here.
  end
end
Run Code Online (Sandbox Code Playgroud)

文档