Create Migration for Column with a Number in the N

2019-07-21 22:47发布

问题:

I'm porting an app into rails and a couple of the columns are named things like

2nd_phone 2nd_address

When I try doing a migration using t.string :2nd_phone

I get syntax error, unexpected tINTEGER, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END

Any ideas how to do this in rals?

回答1:

In your migration file have this with quotes to support starting character as numeric one and then run rake db:migrate

t.string :'2nd_phone'

While doing this way if you want to create new record you need to have like this:

Model.create(:'2nd_phone'=> 'your value')


回答2:

The error you are seeing is because ruby doesn't like the symbol :2nd_phone because ruby doesn't support symbols that start with a number. I think this is going to be the first of many problems you experience with this if you're trying to use the database schema exactly as it is.

You could declare the column with t.string "2nd_phone" which would mean the migration would run. However, you'll still going to get problems with not being able to use the getter and setters for the attribute which rails (activerecord) would provide. I.e. you're not going to be able to do my_thing.2nd_phone, again because ruby doesn't support method names that start with a number.

You could (maybe) access the attributes using the attribute hash (my_thing["2nd_phone"]) but there are plenty of other things that I expect you will run into problems with.

So, all in all, my advice is to change the database schema if you can. second_phone or phone2 would both work.