Create Migration for Column with a Number in the Name

自古美人都是妖i 提交于 2019-12-11 02:23:18

问题


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.



来源:https://stackoverflow.com/questions/29803300/create-migration-for-column-with-a-number-in-the-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!