About products using crud processing and devise (for beginners)

Why I posted this time

Utilizing what I learned at online school I decided to write this as a memorandum. Since it is written by an amateur, I would appreciate it if you could forgive me if there was something different. It's quick, but let's go for the first time.

Development environment

code

rails new App name you want to make-d postgresql

❇︎ Basic rails defaults to SQLite3, so you can specify the database with -d.

Then do

--Make it feel like returning to the folder with the app name you created Example) cd my_favorite

【Terminal】
rails db:create

--Drop the folder of your own app into VS Code. Then you can edit it with VS Code.

Install gem devise

--Write the following in gemfile

【gemfile】

 gem 'devise'

--When the addition is completed, execute the following

【Terminal】

bundle install

Once the gem is installed, enter the commands needed to implement devise's login feature

【Terminal】
 rails g devise:install(Be careful of forgetting the colon)

❇︎ The reason for rails g devise: install is that devise uses a dedicated command and You need to do this because you need to create a config file

Create a devise-only model

【Terminal】
rails g devise user(I don't need a colon)

After finishing, execute the following command


【Terminal】
 rails db:migrate

Then create a navigation bar

--Write the following in application.html.erb

<% if user_signed_in? %>
 <%= link_to "Log out", destroy_user_session_path, method: :delete %>
 <%= link_to "Top", products_path %>
 <%= link_to "To the posting screen", new_product_path %>

<% else %>
 <%= link_to "Login", new_user_session_path %>
 <%= link_to "sign up", new_user_registration_path %>
<% end %>

After implementing the navigation bar, the next step is to create the product model and product controller.

--Write the following

【Terminal】
rails g model product

--Once done, edit the migration file item as follows

class CreateProducts < ActiveRecord::Migration[5.2]
  def change
   create_table :products do |t|
      t.string :name
      t.integer :price
      t.integer :user_id
      #So far
      t.timestamps
    end
  end
end

After executing the above, execute the following

【Terminal】
rails db:migrate

--Edit data in db / seeds.rb

【seeds.rb】
Product.create(name: "Getting Started with Ruby", price: 2500, user_id: 1)
Product.create(name: "Rails basics", price: 2900, user_id: 1)
Product.create(name: "PHP basics", price: 1500, user_id: 1)

After completing the above, enter the following command

【Terminal】
 rails db:seed

--If this does not cause an error, it is successfully registered in the table.

After successfully registering, enter the following command

【Terminal】
rails g controller Products

After entering the command, perform the following processing

--Edit config / routes.rb as follows

 Rails.application.routes.draw do
 root to: 'products#index'
 resources :products
 end

Once the above is done, define the index action

【products_controller.rb】
 class ProductsController < ApplicationController
 def index
  @products= Product.all
  end
 end

After defining the index action, the next step is to create a view file corresponding to it.

【index.html.erb】
<h1>New post list</h1>
   <% if user_signed_in? %>
   <% @products.each do |product| %>
    <p>Product name:<%= product.name %></p>
    <p>Amount of money:<%= product.price %></p>
   <% else %>
Excuse me, but please log in
   <% end %>
 <% end %>

--When you implement the login function with devise, the login / sign-up screen is automatically generated, but it is applicable in views. The file to be used does not exist. Therefore, you cannot make changes to the login screen as it is. If you want to make changes, you need to use the devise command to generate a view file. --Execute the following command to generate a view file for the login screen.

【Terminal】
rails g devise:views

Once you've done the above, it's time to define a new action for Products_controller

【products_controller.rb】
 class ProductsController < ApplicationController
  def new
   @product = Product.new
  end
 end

Creating a view file

--Once you have done the above, create a new post form in new.html.erb in the users directory.

【new.html.erb】
<h1>New post</h1>
<%= form_with model: @product, local: true do |form| %>
<p>Product name:<%= form.text_field :name, required: true %></p>
<p>Amount of money:<%= form.text_field :age, required: true %></p>
<%= form.submit "Send" %>
<% end %>

define create action

【products_controller.rb】
 def create
  Product.create(name: product_params[:name], price: product_params[:price], 
  user_id: current_user.id)
  redirect_to root_path
  end

--Once you can define the create action, the strong parameter is here! Described as follows at the bottom of the products controller

 private
  def product_params
   params.require(:user).permit(:name, :price)
  end

――Explaining this, it says that only (: name,: price) linked to the user model is allowed. Is defining that

After completing the above, write the following command at the top of products_controller

【products_controller.rb】
class ProductsController < ApplicationController
  before_action :move_to_index, except: :index ← Add here

  def index
    @products = Product.all
  end

  def new
    @product = Product.new
  end

  def create
    Product.create(name: product_params[:name], price: product_params[:price], user_id: current_user.id)
  end

  def move_to_index
    redirect_to action: :index unless user_signed_in?← Add here
  end
Omitted below

--If you write this before the action, if you are not logged in, you will not be able to go to other actions and will be forced to go to the index action.

Partially change the route

【routes.rb】
 Rails.application.routes.draw do
 root to: 'products#index'
 resources :products
 resources :users, only: :show ← Add this
 end

--This time, only show action is used in users_controller, so write as above.

I will make a new users controller

【Terminal】
rails g controller Users

Describe the following in the users controller

【users_controller.rb】
 class UsersController < ApplicationController
  def show
   @products = Product.where(user_id: current_user.id)
  end
 end

Describe the following in show.html.erb (userscontroller view file)

【show.html.erb】
<% @products.each do |product| %>
  <p>Product name:<%= product.name %></p>
  <p>price:<%= product.price %></p>
<% end %>

Add the following description to application.html.erb (navigation bar)

<%= link_to 'to My page', user_path(current_user.id) %>


In order to display the ID of the user who purchased in the purchased product list, write as follows in index.html.erb of /views/products

【index.html.erb】
<h1>New post list</h1>
   <% if user_signed_in? %>
    <% @products.each do |product| %>
    <p>Product name:<%= product.name %></p>
    <p>Amount of money:<%= product.price %></p>
    <p>Member No.:<%= product.user.id %></p>   
   <% else %>
Excuse me, but please log in
   <% end %>
 <% end %>

――However, if this is left as it is, an error will occur. What to do from here is the process called association To execute. As an image, an image that combines user and product

First thing to do

--Edit product.rb in app / models as follows

【product.rb】
 class Product < ApplicationRecord
  belongs_to :user ← Describe here
 end

――If you explain, who owns the product? If you think about it, you should think that you are a user. Write like this

What to do next

--Edit user.rb in app / models as follows

【user.rb】
class User < ApplicationRecord 
#Include default devise modules. Others available are:
 #:confirmable, :lockable, :timeoutable, :trackable and :omniauthable
 devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :validatable
 has_many :products ← Describe here
 end

――Explaining, what does user have a lot? If you think that you have a lot of products I'll write it like this

Now that the association is complete, we will make two improvements.

First of all, I wrote the show action of userscontroller earlier, but it is a bit clunky, so change it as follows

【users_controller.rb】
 class UsersController < ApplicationController
 def show
 @products = Product.where(user_id: current_user.id)
  end
 end

--After change

【users_controller.rb】
def show
 @products = User.find(current_user.id)
end

The second point is to change show.html.erb (userscontroller) as follows.

【show.html.erb】
<% @products.each do |product| %>
  <p>Product name:<%= product.name %></p>
  <p>price:<%= product.price %></p>
<% end %>

--After change

【show.html.erb】
<% @user.products.each do |product| %>(←@user.Change to products)
  <p>Product name:<%= product.name %></p>
  <p>price:<%= product.price %></p>
<% end %>

Finally

With this, the implementation of the login function and the rough process of crud have been completed. I wanted to explain the implementation of edit and update actions, the flash function, decoration with bootstrap, etc., but this time I will leave it here. In the future, when creating your own portfolio, when implementing the login function, it is better to implement devise first and then perform crud processing etc., so it may be less likely to get stuck. (I was like that lol) Thank you very much.

Recommended Posts

About products using crud processing and devise (for beginners)
[For beginners] About lambda expressions and Stream API
About for statement and if statement
(For beginners) [Rails] Install Devise
Java for beginners, expressions and operators 1
Java for beginners, expressions and operators 2
About if statement and branch processing
[For Java beginners] About exception handling
Classes and instances Java for beginners
[Ruby on Rails] About bundler (for beginners)
[For beginners] Difference between Java and Kotlin
Impressions and doubts about using java for the first time in Android Studio
About devise
[For beginners] I tried using DBUnit in Eclipse
[For beginners] I tried using JUnit 5 in Eclipse
[For beginners] Test devise user registration with RSpec
Points for coexistence of devise and devise token auth
Beginners try using android studio Part 2 (event processing)
Kantai Collection Java # 1 Classes and Objects [For Beginners]
[For beginners] Procedure for creating a controller using rails