简体   繁体   中英

camelCase column in postgresql database in rails (ActiveRecord)

I have Post model. It has title and body. I want to add short description in there. Although, I know how to do it with snake_case (ie short_description), I wonder if there is any way to create a post with camelCase (ie shortDescription).

This is my schema.rb file

  create_table "posts", force: :cascade do |t|
    t.datetime "created_at",                     null: false
    t.datetime "updated_at",                     null: false
    t.string   "title"
    t.text     "body"
    t.string   "shortDescription"
  end

I added shortDescription to controller and a form. When I go to posts#create, I get the following error.

undefined method `shortDescription'

For now I am going to rollback the database, and create short_description. It is not a big issue, but because of my curiosity for the technology, I would like to know how to use camelCase. (Maybe someday I need to join the db with camelCased attributes with Rails app).

Any advise is appreciated. Thank you!

In Postgres (as well as in the ISO/ANSI standard of SQL language), object names are case-insensitive.

So objectName is the same as objectname , and you must take it into account when deciding to use camel-cased names.

You can tell Postgres, that you do want to use case-sensitive name – just add double quotes around the name: "objectName" . Keep in mind, that later you won't be able to use such object as objectName , it will simply try to find objectname and won't find it, triggerring an error, so using double quotes will be mandatory.

Also, there are some minor caveats when working with double-quoted case-sensitive object names (for instance, psql's \\d command will list your object like this: "public.objectName" , which is not really correct, the correct name is "public"."objectName" , etc).

In few projects, I had camel-style table/column names and it always was some pain, especially when a new developer started to work with such project.

So I'd suggest using underscorded names in SQL always ( object_name ).

It's bad idea. Because postgresql is case-insensitive and then you will be have many problems with this field. So, I think you can create this camelCase field with sql query in your migration. Like this:

"some query text \""+"camelCaseName"+"\" end query text".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM