Allow setting the #id attribute when creating an ActiveRecord

Posted Over 11 years ago. Visible to the public. Deprecated.

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
Last edit
Over 10 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2013-02-11 18:24)