Overriding id on create in ActiveRecord

后端 未结 13 2605
自闭症患者
自闭症患者 2020-11-28 05:07

Is there any way of overriding a model\'s id value on create? Something like:

Post.create(:id => 10, :title => \'Test\')

would be ide

13条回答
  •  野性不改
    2020-11-28 06:00

    This case is a similar issue that was necessary overwrite the id with a kind of custom date :

    # in app/models/calendar_block_group.rb
    class CalendarBlockGroup < ActiveRecord::Base
    ...
     before_validation :parse_id
    
     def parse_id
        self.id = self.date.strftime('%d%m%Y')
     end
    ...
    end
    

    And then :

    CalendarBlockGroup.create!(:date => Date.today)
    # => #
    

    Callbacks works fine.

    Good Luck!.

提交回复
热议问题