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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)