Overriding id on create in ActiveRecord

Viewed 58899

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

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

would be ideal, but obviously won't work.

13 Answers

Try

a_post = Post.new do |p| 
  p.id = 10
  p.title = 'Test'
  p.save
end

that should give you what you're looking for.

Actually, it turns out that doing the following works:

p = Post.new(:id => 10, :title => 'Test')
p.save(false)

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)

you can insert id by sql:

  arr = record_line.strip.split(",")
  sql = "insert into records(id, created_at, updated_at, count, type_id, cycle, date) values(#{arr[0]},#{arr[1]},#{arr[2]},#{arr[3]},#{arr[4]},#{arr[5]},#{arr[6]})"
  ActiveRecord::Base.connection.execute sql
Related