Not following Rails table and field conventions

Whenever we generate a model then Rails expects that the underlying table has following:

1) table name starts with small letter and the word is in plural (ie, customers)

2) a table name that has more than one word in its name then it should be separated by an underscore (ie, line_items)

3) the field names with in the table should also start with small letters.

4) the primary key of the table should be an auto-incremented, integer type and with field name id

5) if you have a foreign key with in that table then it should be in the form table_name_id

If a table follows all the above conventions then the generated model will work straightaway. Otherwise follow these steps

  • If you are not following the conventions 1 & 2 and your table name is something like CustomerRecord instead of customer_records then you have to set the table name within your model just after the class name, like this:

class Customer < ActiveRecord::Base

set_table_name “CustomerRecord”

…..

end

  • If you are not following the convention 4 and your auto-incremented primary key is called Customer_ID instead of id, then do this

class Customer < ActiveRecord::Base

set_primary_key “Customer_ID”

….

end

  • If you are not following convention 5 and your foreign key is named as Customer_Category, then you have to specify that in your model relationship,

class Customer < ActiveRecord::Base

set_table_name “CustomerRecord”

set_primary_key “Customer_ID”

belongs_to :category, :foreign_key => ‘Customer_Category’

….

end

Advertisements

7 thoughts on “Not following Rails table and field conventions

  1. Anh Ta says:

    Seems you miss something, if you’re not following convention 5 you should add category.rb :
    class Category ‘Customer_Category’
    end

    It’s worked with me 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s