Alias Rails columns

Snippet

When working with APIs, sometimes the fields from the APIs are reserved keywords (looking at you, Shopify, and your type fields). When saving the data directly, you don't can't have a field in the database named type, but you don't want to manipulate the parameters and models for every query call. That would suck.

Alias the field instead.

class User < Activerecord::Base
  alias_attribute :new_column_name, :real_column_name
end
 
# specific use case (metafields at Shopify)
ActiveRecord::Schema.define(version: 2022_07_04_191939) do
  create_table "metafields", force: :cascade do |t|
    t.string "namespace"
    t.string "key"
    t.string "value"
    t.string "value_type"
    t.string "variant_type"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
end
 
# aliased
class Metafield < ApplicationRecord
  # the Shopify object has 'type' but 'type' is a DB reserved word
  alias_attribute :type, :variant_type
end

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.