본문 바로가기

카테고리 없음

Generate Model With Foreign Key Rails



Nov 02, 2016  Immigrant currently only looks for foreign keys in ActiveRecord::Base's database. So if a model is using a different database connection and it has foreign keys, Immigrant will incorrectly include them again in the generated migration. Immigrant.ignorekeys can be used to work around this. Changelog License.

  1. Rails Generate Model Reference
  2. Foreign Key Rails
  3. Primary Key
  4. Unique Key

Objectives

After this lesson, developers will be able to:

  • Create a one-to-many relationship between 2 models
  • Perform CRUD actions on two models using rails console
  • Describe primary and foreign keys

Preparation

Before this lesson, developers should already be able to:

  • Access and use rails console
  • Perform CRUD actions on one model

Framing: Review One-to-Many Relationships

Previously, we created a Rails app using an Artist as our model. In this lesson, we're gonna add a Song model that will belong to the Artist. Since an Artist typically has many songs we're gonna create a One to Many Relationship between the two models.

YOU DO- What are some other examples of one-to-many relationships that you can think of?

  • A Post has many Comments
  • A Album has many Songs
  • A Movie has many Actors

In our Muse app, an Artist will have many instances of Song.We need a way to represent this type of many to many relationship!

Primary and Foreign keys

Here is an example of a one-to-many relationship from the Rails Docs.


Note that both authors and books each have their own id field. These are primary keys.

Now, how can we relate the books that belong to a given author? We add an author_id field, or foreign key, to the books table. The author_id will be the id of the author who wrote the book.


Generating the Model / Migration

We can generate the Song model just like our Artist model! If we specify the attributes (i.e.columns on the command line, Rails will automatically generate the correct migration for us.)

YOU DO - Based on what we covered, how can we create an Artist model.. what would be the rails command to create a Song model with title and genre attributes?

  1. From the command line, generate the Song model:

    • We'll see shortly that artist:references will add a foreign key field of artist_id to our songs table

  2. Run rails db:migrate. This will generate a Song model, with artist_id, title, and genre columns. We can look at db/schema.rb file to confirm.


Adding the Active Record Relationships

We need to update our models to indicate the associations between them. For Muse, our models should look like so:

Adding has_many :songs will complete the one-to-many relationship.

Dependent Destroy

Rails

What happens if we delete an Artist? The songs remain. This doesn't make sense right? If we delete an Artist then their Songs should be deleted too? Rails has a way to add this functionality:


Seed some Songs

Cool, like before, let me give you some song data to seed your database with songs:

  1. Add this below your Artist seeds in db/seeds.rb:

  2. We don't want to re-seed the duplicate artists from earlier. So let's drop our database and start over.

    rails db:drop db:create db:migrate db:seed

    Not Recommended: We can run rails db:reset(for drop and create only) Sql server generate primary key scripts.

  3. Cool, let's go into rails c and make sure that our database has our Songs:


CRUD: Let's try it on our Song model

Create

.new + .save

The cool thing about Active Record relationships is that now we can create a new Song directly through the Artist it belongs to:

To save our instance to the database we use .save:


Create a Song for an Artist of your choice using .new and .save.

.create

The create method will both instantiate and save a new record into the database:

The coolest part of this is that Active Record will add the appropriate foreign keyartist_id field into the Song.

Also, what if you don't know the id of the Artist?


Add a Song to your Artist using .create


Read

Or, what if we know the song title and want to find out who the Artist is?

Note.. when we want to return all the artists or songs we use uppercase, as in Song.all. This is because we're asking for all the instances of the Song model/class.

When we want to access the songs for a given artist we use lowercase and plural, as in rihanna.songs.


Rails Generate Model Reference

  • Find the Artist that sings 'Shake It Off'

You can learn more about querying an Active Record model in the Active RecordQuery Interface guide.


Update


  • Choose a Artist and update the attributes of a Song

Delete

Likewise, once retrieved, an Active Record object can be destroyed which removes it from the database.

Let's delete a Song:

Remember the code dependent: :destroy that we added to the Artist model? That bit of code tells Active Record that if we delete an Artist it should also delete all the songs that belong to that Artist.

Let's see it in action. When we delete Rihanna all of her songs are deleted also.

Check out your rails c and note that Active Record is deleting both the Artist and her Songs.

Rails generate model foreign key
  • delete an Artist

Independent Practice (15 mins)

Using Active Record Associations:

  • Create 3 new Songs for an Artist of your choice
  • Update a song's attribute
  • Delete a song you created

Foreign Key Rails


Conclusion (5 mins)

Autodesk 2010 product key generator. In this lesson we:

  • Created a Song model for our Muse app
  • Established a one-to-many relationship between Artist and Song
  • Practiced CRUD with Active Record associations

Primary Key

Labtime

Unique Key

Add onto the books-app you started, that was based on the previous lesson. Go through this lesson and instead of Song add a Book model to your app.