Read more

Allow setting the #id attribute when creating an ActiveRecord

Henning Koch
February 11, 2013Software engineer at makandra GmbH

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).

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2013-02-11 19:24)