Re-open an ActiveRecord model that's provided by a gem

后端 未结 6 1945
旧时难觅i
旧时难觅i 2021-02-10 05:53

I\'m trying to extend an ActiveRecord model (Vote) that a gem (https://github.com/peteonrails/vote_fu) provides to my application. (I.e., there is no vote.rb<

6条回答
  •  孤独总比滥情好
    2021-02-10 06:39

    Your issue might be due to the fact that you are monkey patching the class. When rails tries to reload the constants it is not considering your file.

    Try to use module technique as given below.

    Add a file called lib/vote_fu_extension.rb

    module VoteFuExtension
      def self.included(base)
        base.has_one :activity_stream_event
        base.after_create :create_activity_stream_event
      end
      def create_activity_stream_event
        # something..
      end  
    end
    Vote.send(:include, VoteFuExtension)
    

    Add an initializer called config/initializers/vote_fu.rb

    require "vote_fu_extension"
    

    Note

    If you want to add class methods to the Vote model refer to this answer.

    Shameless plug: My fork of the vote_fu gem has some new features and enhancements.

提交回复
热议问题