Ruby On Rails : Generate proper EER diagram with MySql Workbench

command

$ rails generate model Micropost user:references

adds the line belongs_to :user in the Micropost model and hereby declares as foreign key.

or you can specify that during the creation of migration file

$ rails g migration create_microposts_table user:references

FYI
Declaring the foreign keys using the former method only lets the Rails know about the relationship the models / tables have. The database is unknown about the relationship. Therefore when you generate the EER Diagrams using softwares like MySql Workbench you find that there is no relationship threads drawn between the models. Like in this pic

enter image description here

However, if you use the later method you find that you migration file looks like

def change
    create_table :microposts do |t|
      t.references :user, index: true

      t.timestamps null: false
    end
    add_foreign_key :microposts, :users
end

Now foreign key is set in database level. and you can generate proper EER diagrams. enter image description here

MySql Workbench

Click Database > Reverse Engineer > (set param to connect to DB ) > Next > Next > (Select the database) > Next > Next > Place Imported Object on diagram > Execute > Next > Close >

MySql workbench EER Diagram

MySql workbench EER Diagram

Sources:

http://stackoverflow.com/questions/7861971/generate-model-using-userreferences-vs-user-idinteger/32036637#32036637

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