Rails: Overriding ActiveRecord association method

后端 未结 7 1388
忘了有多久
忘了有多久 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:55

    This may not be helpful in your case but could be useful for others looking into this.

    Association Callbacks: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

    Example from the docs:

    class Project
      has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
    
      def evaluate_velocity(developer)
        ...
      end
    end
    

    Also see Association Extensions:

    class Account < ActiveRecord::Base
      has_many :people do
        def find_or_create_by_name(name)
          first_name, last_name = name.split(" ", 2)
          find_or_create_by_first_name_and_last_name(first_name, last_name)
        end
      end
    end
    
    person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
    person.first_name # => "David"
    person.last_name  # => "Heinemeier Hansson"
    

提交回复
热议问题