Rails:覆盖 ActiveRecord 关联方法 [英] Rails: Overriding ActiveRecord association method

查看:21
本文介绍了Rails:覆盖 ActiveRecord 关联方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法覆盖 ActiveRecord 关联提供的方法之一?

Is there a way to override one of the methods provided by an ActiveRecord association?

例如我有以下典型的多态 has_many :through association:

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

您可能知道,这会向 Story 模型添加大量关联方法,例如标签、标签<<、标签=、标签.空?等.

As you probably know this adds a whole slew of associated methods to the Story model like tags, tags<<, tags=, tags.empty?, etc.

如何覆盖这些方法之一?特别是标签<<方法.覆盖普通的类方法非常容易,但我似乎找不到有关如何覆盖关联方法的任何信息.做类似的事情

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 的块来扩展您与方法的关联.请参阅评论使用块来扩展您的关联"此处.
覆盖现有方法也可以,但不知道是否是个好主意.

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

这篇关于Rails:覆盖 ActiveRecord 关联方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆