6

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!

Bexultan Myrzatay
  • 1,105
  • 10
  • 17
  • Possible duplicate of [rails attribute names camelcase issue](https://stackoverflow.com/questions/36859240/rails-attribute-names-camelcase-issue) – 31piy Jul 22 '17 at 11:01
  • 1
    what is a use case you're envisioning? you can always operate on the name in the code if you just need a camel cased representation of the column name – m. simon borg Jul 22 '17 at 12:50

2 Answers2

10

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

Nick
  • 2,423
  • 13
  • 21
1

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".
Leo
  • 1,673
  • 1
  • 13
  • 15