Getting started with Ruby on Rails: A blog app (Part 2)
Add authentication with devise

add devise gem to your gemfile

gem 'devise'

run bundle install to install devise into your app, and complete the installation using the following command. you can learn more about the devise gem here.

rails generate devise:install

now lets add users into our app, as for me I will call them authors

rails generate devise author

and well now migrate our database

rails db:migrate

in our app, we only want authors(users) who have logged into our app to post articles, so we need to add some restrictions. at the very top of our app/controllers/articles_controller.rb, add this line.

before_action :authenticate_author!, except: [:show, :index]

Its important for it to be at the top of the file as rails follows top to bottom order when it comes to executing controller restrictions. here we are restricting every other action except showing list of articles or reading an article.

2. Add associations

here we going to link our authors with articles. typically, authors can post multiple articles, but an article can only have one author. so we have a one-to-many relationship in our case.

in app/models/Article.rb

class Article < ApplicationRecord belongs_to :author end

in app/models/Author.rb

class Author < ApplicationRecord has_many :articles end

create a new migration from your terminal to add author_id to article.

here will will add author id, which will be an integer

rails g migration add_author_id_to_articles

now in root folder/db/migrate, you will see the migration file. mine looks like this

class AddAuthorIdToArticles < ActiveRecord::Migration[6.0] def change add_column :articles, :author_id, :integer end end

Don’t forget to run the database migrations with rake db:migrate

now in our articles controller, edit the create action, and add this line.

# POST /articles.json def create @article = Article.new(article_params) @article.author = current_author #add this line respond_to do |format| if @article.save format.html { redirect_to @article, notice: 'Article was successfully created.' } format.json { render :show, status: :created, location: @article } else format.html { render :new } format.json { render json: @article.errors, status: :unprocessable_entity } end end end

here we are associating a new article with the current logged in user. with this, you can call author.articles, and it will return a list of all articles by the user.

i wont go into design, but i have attached my final app screenshots. you can also find this code on GitHub.
['Brian Ngeywo']
['Beginner Rails', 'Rubygems', 'Devceld Backend', 'Ruby on Rails']