Search code examples
ruby-on-railsscaffoldingrowid

change id back to rowid after 'rails generate scaffold scaffoldname name:string id:integer'


I've got a problem with an id column created with a scaffold. I generated a scaffold with following command:

rails generate scaffold scaffoldname name:string id:integer

I used that id column for a relation which I wanted to use for a dropdown menu with collection_select. Afterwards I realized that generating an id is unnecessary because of the id which rails creates automatically for each table.

When I wanted to call the related table with the self-created id this is of course possible with

class.relatedClass.id

Afterwards I realized that this command is also possible in a table where rails created the id, although the column is named "rowid" in the table.

So i thought that It should be possible to delete the self-created id column with a migration. The way I thought about this was, that rails should then use automatically the rowid for the relation. But after deleting the self-created id there are errors all around. Rails refuses to use the 'rowid' column automatically although it does it in case there was no id column specified in the scaffold command.

How do I delete that self-created id column in a way that rails uses their own created rowid afterwards when calling class.relatedClass.id?


Solution

  • Run this in rails terminal -

    rails g migration remove_id_from_scaffoldname id:integer
    
     rails g migration add_rowid_to_scaffoldname rowid:integer
    

    This will create two migration files - one to remove id field and the other to add the rowid field.

    Then run this in rails terminal -

       rake db:migrate
    

    Also note that rails will create id field automatically but not the rowid as your primary key. To restrict rails to use your defined primary key you have to define so explicitly like this here -

    Your Migration file -

    create_table :tablename, :primary_key => :rowid do |t|
     # ...
    end
    

    Your Model -

    class ModelName< ActiveRecord::Base
      self.primary_key = "rowid"
      ...
    end
    

    Note: It is a good practice to use rails auto generated id as a primary key unless otherwise you have a valid reason to do so.