简体   繁体   中英

Before Create in Active Record

I would like to setup a before_create for all of my modules

what i have been trying is:

module ActiveRecord
  module UserMonitor
    require 'securerandom'

    before_create :attach_uuid
      def attach_uuid
      self.uuid = SecureRandom.uuid.gsub("-","")
    end
  end
end

This does not seem to be working. if i go into each module and add it in there it works, but i want to do it on a global scale.

Any thoughts or ideas on how i can achieve this in this manner? i know i could do it in triggers and such but i don't want to go that route and i would like to avoid hitting every module/class in case i need to change something.

Currently using Ruby 1.9.3 Can not currently upgrade my app until i make future code changes.

Thanks!

An other solution - I use, is to put the logic for UUID in an own module, that you include. I already have some (class-) methods I add to my AR, like set_default_if , so it was a good place for me.

module MyRecordExt
    def self.included base
        base.extend ClassMethods   # in my case some other stuff 
        base.before_create :attach_uuid # now add the UUID 
    end

    def attach_uuid
        begin
            self.uuid = SecureRandom.uuid
        rescue
            # do the "why dont we have a UUID filed?" here
        end
    end


    # some other things not needed for add_uuid
    module ClassMethods
        include MySpecialBase # just an eg.   

        def default_for_if(...)
            ...
        end
    end
end         

and then

class Articel < ActiveRecord::Base
    include MyRecordExt
    ...
end 

In general I avoid doing something for ALL models modifying AR base - I made the first bad experience with adding the UUID to all, and crashed with devise GEMs models ...

If you define attach_uuid in the ActiveRecord module, can't you just call the before_create :attach_uuid at the top of each controller? This is DRY.

Is there a UserMonitor controller that you could add it to?

class UserMonitor < ActiveRecord::Base
  before_create :attach_uuid
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM