Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Overriding Name Conventions for table name and primary key in rails models

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 713
    Comment on it

    Hi friends,

    Today we are going to talk about overriding the default naming conventions for table name and primary key in rails model. Before switching directly to the topic lets take a look to the summary of default naming conventions for database and models of rails and why we need to override this.

    Summarization of default naming conventions in rails

    • The name of tables are in plural and their associated classes has the name in singular form of table name
    • Primary key of the table is to be named id
    • A foreign key of a model looks like modelname_id here modelname represents the model for which it is a primary key

    So after looking towards the conventions lets know why we need to override these conventions. So many times we have a legacy database and we don't want to create new database or change the table names according to conventions or we don't have rights to alter tables. One more reason can be if someone doesn't like naming conventions of rails and want to use his own conventions, so for those requirement Rails allows to change the naming conventions of tables and primary key

    Suppose our table name is our_findnerd and class name is Findnerd and primary key is my_findnerd_id then we need to change in the Findnerd model as:

        class Findnerd < ActiveRecord::Base
          self.table_name = "our_findnerd"
          self.primary_key = "my_findnerd_id"
        end
    


    Note: Hope it is useful for you.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: