Rails: Overriding ActiveRecord association method

后端 未结 7 1396
忘了有多久
忘了有多久 2020-12-05 02:21

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

Say for example I have the following typical polymorphic has_many :through ass

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 02:47

    If you want to access the model itself in Rails 3.2 you should use proxy_association.owner

    Example:

    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
    

    See documentation

提交回复
热议问题