Allow setting the #id attribute when creating an ActiveRecord

This is only relevant for Rails 2 and Rails 3.

When creating an ActiveRecord with .new, .create or create!, you cannot set the ID attribute (note: When using Machinist's .make Show archive.org snapshot you can).

This is because even when you are not using attr_protected or attr_accessible, some attributes are always protected. These attributes are #id and #type.

If you want to allow setting #id on .new, .create or create! you can include the attached module in order to whitelist #id on a model of your choice like this:

class MyModel < ActiveRecord::Base
  include AllowSettingIdOnCreate
end

Note that your controllers should always whitelist the attributes they set on model records.

Henning Koch About 11 years ago