[RUBY] I want to implement a product information editing function ~ part1 ~

Premise

--Use ruby on rails 6.0.0. --User functions are assumed to be introduced by devise. --All view files are in haml format. ――By the way, I'm using MacBook Air (Retina, 13-inch, 2020).

Introduction

I am making a copy site of a certain flea market site for programming learning. I implemented a product information editing function, but I had a hard time posting multiple images, so I decided to write it as a reference. Although it is not a big amount, it is divided into parts so that you can get a sense of accomplishment when you see it later. please forgive me. (I wrote a lot! I want to be) I don't think there is any particular part that gets stuck in part1, but since it will be the foundation for part2 and beyond, I will write about warming up.

Specification

--You can change the information registered in the product one by one. --Only the user who registered the product can edit the product information. --Images can be replaced one by one. --Already registered information such as product names and images will be displayed in advance on the edit screen. --Perform error handling.

(I will post a reference image when the markup is completed)

procedure

1, Creating a base controller and model. 2, Implemented image posting by associating the image table. 3, Introduced jQuery to implement posting of multiple images. 4, Adjustment on the edit screen. 5, Preview the image.

We will implement each of these five steps separately.

Well then

To implement

First, solidify the basic part. First from the terminal.

$ rails g contoroller products $ rails g model product $ rails db:migrate

It's the usual flow. Details such as database creation and migration file description are omitted.

Let's start with the root file.

app/config/routes.rb


Rails.application.routes.draw do
  root "products#index"
  resources :products
  devise_for :users, controllers: {
    registrations: 'users/registrations'
  }
end

The devise part is related to the user functions that have been implemented in advance, so you don't have to worry about it. No detailed explanation is necessary here either. I made a basic action with resources and specified an index action in the root path. (This time, destroy and show are not used, so you can exclude them.)

Next is the description of the controller.

app/controllers/products_controller.rb


class ProductsController < ApplicationController
  before_action :ensure_current_user, only[:edit, :update]
  before_action :set_product, only[:new, :create, :edit, :update]

  def index
    @products = Product.all
  end

  def new
    @prodcut = Product.new
  end
  def create
    @product = Product.new(product_params)
    if @product.save
      redirect_to products_path
    else
      render :new
    end
  end

  def edit
  end
  def update
    if @product.update(product_params)
      redirect_to products_path
    else
      render :edit
    end
  end

  private
  def product_params
    params.require(:product).permit(:name).merge(user_id: current_user.id)
  end
  def ensure_current_user
    product = Product.find(params[:id])
    if product.user_id != current_user.id
      redirect_to action: :index
    end
  end
  def set_product
    @product = Product.find(params[:id])
  end
end

Is it such a place for the time being? I will explain step by step.

First of all, about the basic actions.

@products = Product.all

There is no problem with index, all records registered in the product table are fetched.

@prodcut = Product.new

Products are registered in new and create. Create a new object in model .new and assign the form values to it.

def product_params  params.require(:product).permit(:name).merge(user_id: current_user.id) end

The data sent in this way is received by the product_params method. It's a strong parameter that everyone loves. The column is only name because it only implements the minimum functionality.

if @product.save  redirect_to products_path else  render :new end

The following if statement, this is the one called error handling. If the process succeeds, the index is displayed, and if the process fails, new is displayed again. There are some complicated parts in the concept, but I think you are already familiar with the functions.

@product = Product.find(params[:id])

Next is the edit and update actions, but what we are doing is the same as before. The difference from create is that you don't need to create a new object because the data already exists, and you bring the product selected by the find method.

def ensure_current_user  product = Product.find(params[:id])   if product.user_id != current_user.id   redirect_to action: :index  end end

Finally, the ensure_current_user method. It may seem difficult at first glance, but the process is very easy. The point is that if the user information of the selected product and the logged-in user information are different, you cannot edit it.

Now that the description of the controller is finished, it's time to write the view file.

haml:app/view/products/index.html.haml


- if user_signed_in?
  - @products.each do |product|
    - if product.user_id == current_user.id
      = link_to edit_product_path(product.id) do
        #{product.name}
  = link_to("Listing", new_product_path)

  %h2 logged in
  = link_to 'Log out', destroy_user_session_path, method: :delete

- else
  %h2 not logged in
  = link_to 'sign up', new_user_registration_path
  = link_to 'Login', new_user_session_path

Let's start with the index, but only the first six lines should be noted. Is the user logged in? Is the product registered by the user? Under the two conditions such as, the edit and new paths are displayed.

haml:app/views/products/_form.html.haml


= form_with model: @product, local: true do |f|
  = f.text_field :name, placeholder: 'name'
  = f.submit 'SEND'

I don't think there is anything special to explain here either. You use the form_with method to send data to the product model. All you have to do is display this as a partial template in new.html.haml and edit.html.haml as a render.

Finally

At this point, you have implemented the ability to create product data and edit it. (The column is just the name, but ...)

In the specifications,

--You can change the information registered in the product one by one. --Only the user who registered the product can edit the product information. --Perform error handling.

It means that we were able to clear these three. In the next part, we will be able to add images (image table), so please keep in touch.

I want to implement the product information editing function ~ part2 ~

Recommended Posts

I want to implement a product information editing function ~ part1 ~
"Teacher, I want to implement a login function in Spring" ① Hello World
I want to define a function in Rails Console
I want to add a delete function to the comment function
I want to make a function with kotlin and java!
I want to add a browsing function with ruby on rails
I want to develop a web application!
I want to write a unit test!
[Ruby] I want to do a method jump!
[Android] Implement a function to display passwords quickly
I want to simply write a repeating string
I want to design a structured exception handling
I tried to implement a server using Netty
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
I want to use a little icon in Rails
I want to monitor a specific file with WatchService
I tried to make a login function in Java
[Java] I tried to implement Yahoo API product search
I want to add a reference type column later
I want to click a GoogleMap pin in RSpec
I want to connect to Heroku MySQL from a client
I want to create a generic annotation for a type
I tried to make a message function of Rails Tutorial extension (Part 1): Create a model
I made a function to register images with API in Spring Framework. Part 1 (API edition)
I want to implement it additionally while using kotlin on a site running Java
I tried to implement the like function by asynchronous communication
[Java] I want to convert a byte array to a hexadecimal number
I want to randomly generate information when writing test code
I want to find a relative path in a situation using Path
I want to convert characters ...
I want to expand the clickable part of the link_to method
I want to make a specific model of ActiveRecord ReadOnly
[Swift] I tried to implement the function of the vending machine
I want to make a list with kotlin and java!
I want to call a method and count the number
I want to create a form to select the [Rails] category
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I want to give a class name to the select attribute
I want to create a Parquet file even in Ruby
I tried to make a message function of Rails Tutorial extension (Part 2): Create a screen to display
I tried to implement a buggy web application in Kotlin
I want to implement various functions with kotlin and java!
I made a function to register images with API in Spring Framework. Part 2 (Client Edition)
[Rails] I tried to implement "Like function" using rails and js
I want to use FireBase to display a timeline like Twitter
I want to recursively search for files under a specific directory
[Rails] A simple way to implement a self-introduction function in your profile
I want to create a chat screen for the Swift chat app!
I want to make a button with a line break with link_to [Note]
I want to use swipeback on a screen that uses XLPagerTabStrip
[Ruby] I want to put an array in a variable. I want to convert to an array
I made a reply function for the Rails Tutorial extension (Part 1)
I tried to implement the image preview function with Rails / jQuery
I made a reply function for the Rails Tutorial extension (Part 5):
I want to extract between character strings with a regular expression
I tried to make a group function (bulletin board) with Rails
Swift: I want to chain arrays
Try to implement iOS14 Widget function
I want to convert InputStream to String
I want to docker-compose up Next.js!
I made a simple recommendation function.