Overriding id on create in ActiveRecord

后端 未结 13 2583
自闭症患者
自闭症患者 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 05:46

    As Jeff points out, id behaves as if is attr_protected. To prevent that, you need to override the list of default protected attributes. Be careful doing this anywhere that attribute information can come from the outside. The id field is default protected for a reason.

    class Post < ActiveRecord::Base
    
      private
    
      def attributes_protected_by_default
        []
      end
    end
    

    (Tested with ActiveRecord 2.3.5)

提交回复
热议问题