replicate icon indicating copy to clipboard operation
replicate copied to clipboard

Does not load object primary key in Rails 4 with postgres

Open zinkkrysty opened this issue 11 years ago • 2 comments

In database setups where the primary key is set to auto_increment, it excludes the id when loading the object into the database.

INSERT INTO "items" ("field_1", "field_2", "field_3") VALUES ($1, $2, $3) 

but no trace of id (item's primary key)

zinkkrysty avatar Nov 20 '14 17:11 zinkkrysty

I just saw this in the source code, does this mean it is automatically set to false?

https://github.com/rtomayko/replicate/blob/master/lib/replicate/active_record.rb#L219

      # Set or retrieve whether replicated object should keep its original id.
      # When not set, replicated objects will be created with new id.
      def replicate_id(boolean=nil)
        self.replicate_id = boolean unless boolean.nil?
        @replicate_id.nil? ? superclass.replicate_id : @replicate_id
      end

      # Set flag for replicating original id.
      def replicate_id=(boolean)
        self.replicate_natural_key = [:id] if boolean
        @replicate_id = boolean
      end

https://github.com/rtomayko/replicate/blob/master/lib/replicate/active_record.rb#L384

::ActiveRecord::Base.replicate_id           = false

How do I set it so it keeps the original ID?

zinkkrysty avatar Nov 20 '14 17:11 zinkkrysty

Probably

class ActiveRecord::Base                                                                                                                                                                       
  def self.replicate_id                                                                                                                                                                        
    true                                                                                                                                                                                       
  end                                                                                                                                                                                          
end

for all, and for a specific model:

class Article < ActiveRecord::Base
  replicate_id true
end

pirj avatar Nov 23 '15 09:11 pirj