Ruby on rails learning record -2020.10.09

Bulletin board with a function only when logging in Creating a one-line bulletin board ```$ cd bbs_users $ rails g scaffold article user_id:integer content:string $ rails db:migrate ```

Input of initial data

db/seeds.rb


Article.create(user_id: 1, content: 'hello world')
Article.create(user_id: 1, content: 'hello paiza')
Article.create(user_id: 2, content: 'World of Hello, everyone')

Reflected in database

$ rails db:seed

Allow only certain actions to be performed at login

articles_controller.rb


before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_action :set_article, only: [:show, :edit, :update, :destroy]

Association of Articles model and User model

model/article.rb


class Article < ApplicationRecord
    belongs_to :user
end

Displaying the poster's email address

views/articles/index.html.erb


<table>
  <thead>
    <tr>
      <th>User</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @articles.each do |article| %>
      <tr>
        <td><%= article.user.email %></td>
        <td><%= article.content %></td>
        <td><%= link_to 'Show', article %></td>
        <td><%= link_to 'Edit', edit_article_path(article) %></td>
        <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

Display navigation in common

app/views/layouts/application.html.erb


<body>
  <% if user_signed_in? %>
    Logged in as <strong><%= current_user.email %></strong>.
    <%= link_to "Settings", edit_user_registration_path %> |
    <%= link_to "Logout", destroy_user_session_path, method: :delete %>
  <% else %>
    <%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %> |
    <%= link_to "Login", new_user_session_path, :class => 'navbar-link' %>
  <% end %>
  <p class="notice"><%= notice %></p>
  <p class="alert"><%= alert %></p>
  <%= yield %>
</body>

Add column to User model

string


$ rails db:migrate

Added "name" column to sign-up screen

app/views/devise/registrations/new.html.erb


<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>

Added "name" column to the user information change screen

app/views/devise/registrations/edit.html.erb


<div class="field">
  <%= f.label :name %><br />
  <%= f.text_field :name %>
</div>

Change the user name of the User model

Save name column in controller

app/controllers/application_controller.rb


before_action :configure_permitted_parameters, if: :devise_controller?

protected

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up, keys: [:name])
  devise_parameter_sanitizer.permit(:account_update, keys: [:name])
end

Show username in navigation login information

app/views/layouts/application.html.erb


<% if user_signed_in? %>
  Logged in as <strong><%= current_user.name %></strong>.
  <%= link_to "Settings", edit_user_registration_path, :class => "navbar-link" %> |
  <%= link_to "Logout", destroy_user_session_path, method: :delete, :class => "navbar-link" %>
<% else %>
  <%= link_to "Sign up", new_user_registration_path, :class => 'navbar-link' %> |
  <%= link_to "Login", new_user_session_path, :class => 'navbar-link' %>
<% end %>

Display name column in post list

views/articles/index.erb.html


<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Content</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @articles.each do |article| %>
      <tr>
        <td><%= article.user.name %></td>
        <td><%= article.content %></td>
        <td><%= link_to 'Show', article %></td>
        <td><%= link_to 'Edit', edit_article_path(article) %></td>
        <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

Display name column on post details screen

views/articles/show.erb.html


<p>
  <strong>User:</strong>
  <%= @article.user.name %>
</p>

Modify the new post form and remove user_id

app/views/articles/_form.html.erb


<%= form_with(model: article, local: true) do |form| %>
  <% if article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% article.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :content %>
    <%= form.text_field :content, id: :article_content %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

Modify create method

app/controllers/articles_controller.rb


# POST /articles
# POST /articles.json
def create
  @article = Article.new(article_params)
  @article.user_id = current_user.id

Modify update method

app/controllers/articles_controller.rb


def update
    if @article.user_id == current_user.id
      respond_to do |format|
        if @article.update(article_params)
          format.html { redirect_to @article, notice: 'Article was successfully updated.' }
          format.json { render :show, status: :ok, location: @article }
        else
          format.html { render :edit }
          format.json { render json: @article.errors, status: :unprocessable_entity }
        end
      end
    else
        redirect_to @article, notice: "You don't have permission."
    end
end

Modify destroy method

app/controllers/articles_controller.rb


def destroy
  if @article.user_id == current_user.id
    @article.destroy
    msg = "Article was successfully destroyed."
  else
    msg = "You don't have permission."
  end
  respond_to do |format|
    format.html { redirect_to articles_url, notice: msg }
    format.json { head :no_content }
  end
end

fix update action

app/controllers/articles_controller.rb


def update
    if @article.user_id == current_user.id
      respond_to do |format|
        if @article.update(article_params)
          format.html { redirect_to @article, notice: 'Article was successfully updated.' }
          format.json { render :show, status: :ok, location: @article }
        else
          format.html { render :edit }
          format.json { render json: @article.errors, status: :unprocessable_entity }
        end
      end
    else
        redirect_to @article, notice: "You don't have permission."
    end
end

Modify the destroy action

app/controllers/articles_controller.rb


def destroy
  if @article.user_id == current_user.id
    @article.destroy
    msg = "Article was successfully destroyed."
  else
    msg = "You don't have permission."
  end
  respond_to do |format|
    format.html { redirect_to articles_url, notice: msg }
    format.json { head :no_content }
  end
end

View post list

app/views/articles/index.html.erb


<% if user_signed_in? && article.user_id == current_user.id %>
    <td><%= link_to 'Edit', edit_article_path(article) %></td>
    <td><%= link_to 'Destroy', article, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>

Modify the details screen

app/views/articles/show.html.erb


<% if user_signed_in? && @article.user_id == current_user.id %>
    <%= link_to 'Edit', edit_article_path(@article) %> |
<% end %>
<%= link_to 'Back', articles_path %>

Recommended Posts

Ruby on rails learning record -2020.10.04
Ruby on rails learning record -2020.10.05
Ruby on rails learning record -2020.10.09
Ruby on rails learning record-2020.10.07 ②
Ruby on rails learning record-2020.10.07 ①
Ruby on rails learning record -2020.10.06
Ruby on Rails basic learning ①
Ruby on Rails Elementary
Ruby on Rails basics
[Ruby on Rails] About Active Record callbacks
Ruby On Rails Association
Portfolio creation Ruby on Rails
[Ruby on Rails] Debug (binding.pry)
Ruby on Rails config configuration
[Ruby on Rails] about has_secure_password
Commentary on partial! --Ruby on Rails
Cancel Ruby on Rails migration
Ruby on Rails validation summary
Ruby on Rails Basic Memorandum
Ruby learning 4
Ruby on Rails5 Quick Learning Practice Guide 5.2 Compatible Chapter2
Ruby learning 3
Ruby learning 2
Ruby on Rails5 Quick Learning Practice Guide 5.2 Compatible Chapter3
Ruby learning 6
Ruby learning 1
Ruby on Rails Overview (Beginner Summary)
[Ruby on Rails] Read try (: [],: key)
Installing Ruby + Rails on Ubuntu 18.04 (rbenv)
[Ruby on Rails] Introduced paging function
Basic knowledge of Ruby on Rails
Progate Ruby on Rails5 Looking Back
How to use Ruby on Rails
[Ruby on Rails] Add / Remove Columns
Ruby on Rails Japanese-English support i18n
(Ruby on Rails6) "Erase" posted content
[Ruby on Rails] CSV output function
Ruby on Rails 6.0 environment construction memo
[Ruby on Rails] What is Bcrypt?
[Ruby on Rails] Confirmation page creation
Ruby On Rails devise routing conflict
[Ruby on Rails] Comment function implementation
[Ruby on Rails] DM, chat function
[Ruby on Rails] Convenient helper method
[Ruby on Rails] Stop "looping until ..."
Ruby on Rails record search, create if not find_or_create_by method
[Ruby on Rails] Introduction of initial data
[Ruby on Rails] Search function (not selected)
[Rails] Addition of Ruby On Rails comment function
[Ruby on Rails] Creating an inquiry form
Ruby on Rails6 Practical Guide cp13 ~ cp15 [Memo]
Ruby Learning # 13 Arrays
[Ruby on Rails] View test with RSpec
[Ruby on Rails] Code check using Rubocop-airbnb
Ruby Learning # 1 Introduction
[Ruby on Rails] 1 model CRUD (Routing Main)
Ruby Learning # 34 Modules
Ruby on Rails installation method [Mac edition]
[Ruby on Rails] model, controller terminal command
Let's summarize "MVC" of Ruby on Rails
Ruby on Rails model creation / deletion command