Let's go back to the blog_app
we built over the weekend that already has both users
and articles
and integrate some of our knowledge of the Rails associations. This will require some mind numbing and frustrating refactoring, so stay diligent, and work together.
Add a one-to-many
assocciation betweeen articles
and users
. This means we can get rid of the silly author
column in the Article
model and use the user
.
-
Let's remove the
author
column from our article by generating a migrationrails g migration RemoveAuthorFromArticles author:string
and then migrate
rake db:migrate
-
Let's also add
user_id
foriegn key to theArticle
model by using a migration.rails g migration AddUserIdToArticles user_id:integer
and be sure to migrate
rake db:migrate
-
Use your knowledge of
one-to-many
to implement the association in theuser
andaritcle
modelsclass Library < ActiveRecord::Base has_many :articles end
and also
class Article < ActiveRecord::Base belongs_to :user end
-
First go through all your views and remove all the erb that renders
article.author
-
In the
ArticlesController
change thecreate
method to use thecurrent_user.articles.create
to create a newarticle
. We don't want to doArticle.create
anymore. -
In the
UsersController
show page render thecurrent_user.articles
.