ruby-on-rails - rails : Overriding ActiveRecord association method

标签 ruby-on-rails ruby activerecord overriding

有没有办法覆盖 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/

相关文章:

ruby-on-rails - 将参数括起来以确保该 block 将与方法调用相关联

ruby-on-rails - 如何在 Rails View 中使用 Ruby 常量?

ruby - 在 Rails 中使用 class << self 自动加载类

ruby - 如何测试使用 rspec 的 block 的函数

ruby-on-rails - 如何让 Phusion Passenger 使用正确版本的 Ruby?

ruby-on-rails - 如何删除 ActiveRecord 对象?

ruby-on-rails - 在不保存模型的情况下更改 Rails 中的枚举值

ruby-on-rails - 根据其子项(或没有子项)的属性的 Rails 范围

ruby-on-rails - 隐藏 ActiveRecord 模型中的属性

javascript - 如何触发 best_in_place 事件