Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e. short_description), I wonder if there is any way to create a post with camelCase (i.e. 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!

like image 916
Bexultan Myrzatay Avatar asked Jul 22 '17 10:07

Bexultan Myrzatay


2 Answers

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).

like image 71
Nick Avatar answered Sep 29 '22 07:09

Nick


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".
like image 24
Leo Avatar answered Sep 29 '22 06:09

Leo