Adam Templeton
Adam Templeton

Reputation: 4617

How can I map strings with periods to symbols in a Rails 5 database migration?

I have a PSQL database I need to pull data from for a Rails 5.4 application. I have zero control over this database, including the naming conventions.

In this PSQL database, let's say there is a table called warehouse_items with an attribute named ITEM_WH.SERIAL that contains a warehouse item's serial number.

Then, let's say I try to create a migration for this table that incorporates this attribute as the primary key:

  def change
    create_table :warehouse_items do |t|
      t.string :ITEM_WH.SERIAL, null: false
    end
  end

The scene ends badly, as you might imagine, in a cavalcade of anger and fear. The .SERIAL is interpreted as a method on the symbol :ITEM_WH, rather than as a cohesive whole :ITEM_WH.SERIAL.

I know I can use strings instead of symbols here (i.e. 'ITEM_WH.SERIAL'), but I've heard that's less efficient.

Is there some way to map the string in the SQL database to a symbol in the migration, basically telling my application that, "Yes, I know the database attribute is ITEM_WH.SERIAL and I want you to pull that information, but please map it to the symbol :item_wh_serial in your own schema"?

Is it even that bad to use strings instead of symbols in a database migration?

What are my options here?

Upvotes: 0

Views: 232

Answers (1)

Jared Beck
Jared Beck

Reputation: 17538

In this PSQL database, [there is a column] named ITEM_WH.SERIAL ..

  t.string :ITEM_WH.SERIAL, null: false

The scene ends badly .. [it is a ruby syntax error]

Option 1: fix the symbol literal

t.string :"ITEM_WH.SERIAL", null: false

Option 2: use a string instead of a symbol

t.string "ITEM_WH.SERIAL", null: false

Upvotes: 1

Related Questions