Rails: can not be used with :count => 1. key ‘one’ is missing.

If you ever encountered this error probably you are trying to add/access a I18n key for a `enum` attribute. For example if my model has a `enum` value like below.

class Shipment < ApplicationRecord
   enum delivery_option: {"arrival_notice":"arrival_notice", "arrival_schedule": "arrival_schedule"}
end

If we want to internationalize the `values` as

Call/notify before delivery and Delivery appointment required

. In your en.yml you need to specify as below.

en:
  activerecord:
    attributes:
      shipment:
        delivery_option:
          one: 'Delivery Option'
          arrival_notice: "Call/notify before delivery"
          arrival_schedule: "Delivery appointment required"

I18n expects the name of-the field as the first key/value.If you forget that then you see this error. Happy coding!

Adding indexes to columns in rails migration

I tried to add an index to a column and failed. After digging deeper these are my findings.

In rails migration if we want to add index to a column there are 2 ways.

  • While creating a new table you can specify
    index: true

eg:

def change
  create_table :users do |t|
    t.string :name, limit: 30, null: false
    t.string :password, null: false, limit: 20
    t.string :email, null: false, limit: 20, index: true
  end
  • In all the remaining scenarios(add/update new column) we need to explicitly mention
    add_index

eg:

def change
  add_column :users, :employee_number, :integer
  add_index :users, :employee_number
end

index: true works only when creating new table. Hoping this is helpful.

Rails accepts_nested_attributes_for not deleting/removing associations.

Trying to save some others going through this pain. I have a parent and child associations both in the same form.

In parent i added `accepts_nested_attributes_for :child` and thought its going to take care of everything which is wrong. This helps in `create` and `update` but not in `delete`. To delete the child association you need to mention allow_destroy: true

accepts_nested_attributes_for :child, allow_destroy: true