Last active
February 20, 2023 12:58
Generate models with associations using rails generators, enabling custom class_name, foreign keys, and indices.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Here's how it flows: | |
1. Create models: | |
``` | |
rails g model User name --no-test-framework --no-assets | |
rails g model Post content --no-test-framework --no-assets | |
rails g model Address city --no-test-framework --no-assets | |
``` | |
2. Create and migrate db: | |
``` | |
rake db:create db:migrate | |
``` | |
(`db:setup` does not create a new `schema.rb`, which is problematic at resetting the db so it's better to have this habit of using the two above commands. `rake db:reset` is in this case also a worse choice as it does not run migrations.) | |
3. Modify associations in models: | |
``` | |
#user.rb | |
has_many :posts, foreign_key: :author_id, dependent: :destroy | |
has_one :address, foreign_key: :owner_id | |
``` | |
``` | |
#post.rb | |
belongs_to :author, class_name: 'User' | |
``` | |
``` | |
#address.rb | |
belongs_to :owner, class_name: 'User' | |
``` | |
4. Add references in db: | |
`rails g migration AddReferences`: | |
``` | |
def change | |
add_reference :posts, :author, index: true | |
add_reference :addresses, :owner, index: true | |
end | |
``` | |
5. Add foreign keys: | |
`rails g migration AddForeignKeys`: | |
``` | |
def change | |
add_foreign_key :posts, :users, column: :author_id | |
add_foreign_key :addresses, :users, column: :owner_id | |
end | |
``` | |
6. Migrate and check if everything works fine: | |
``` | |
rake db:migrate | |
rails c | |
User.first | |
Post.first | |
Address.first | |
User | |
Post | |
Address | |
User.create!(name: 'Maciek') | |
Post.create!(content: 'First post', author: User.first) | |
Address.create!(city: 'Mikolow', owner: User.first) | |
Post.first.author | |
Address.first.owner | |
User.first.posts | |
User.first.address | |
``` | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment