Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to generate multi-word reference fields in rails

rails generate model product name:string twoWord:string twoWordRef:references

produces the following migration file

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.string :twoWord
      t.references :twoWordRef, index: true

      t.timestamps null: false
    end
    add_foreign_key :products, :twoWordRefs
  end
end

I thought that field names were supposed to be snake case, not camel case, yet rails generate model is producing camel case field names in the migration file. I think I am following the examples on my generate command.

I am also finding issues later on when I try to update via reference where rails assumes the foreign key is in snake case and can't find my foreign key in the table.

What am I doing wrong? Thanks

like image 811
lxmas Avatar asked Dec 08 '22 04:12

lxmas


1 Answers

Rails automatically generate the database tables in snake case. For example if your model is TestModel corresponding table in database will be test_models. However same is not the case for attributes.

Do this instead:

rails generate model product name:string two_word:string two_word_ref:references

Update

This is completely out of scope for what OP asked, but I thought sharing this might be helpful if you are starting Rails. Rails uses a few conventions when naming models and tables (like singular name for model and plural for table). For this it uses ActiveSupport::Inflector module.

The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept in inflections.rb.

You can use its classify and tableize methods to validate corresponding names. Eg:

"test_models".classify
# => "TestModel"

"TestModel".tableize
# => "test_models"
like image 72
shivam Avatar answered Apr 30 '23 03:04

shivam