【Rails】쿠폰 기능의 실현(일괄 처리를 이용한 자동 삭제 기능이 포함)

목표



개발 환경


・Rubby:2.5.7
・Rails:5.2.4
・Vagrant:2.2.7
・VirtualBox:6.1
・OS:macOS Catallina

전제 조건


다음은 이미 실현되었다.
슬림 가져오기
Bootstrap3 가져오기
로그인 기능 설치
발언 기능 설치

이루어지다


1. 열 추가


단말기
$ rails g model Coupon user_id:integer is_valid:boolean limit:integer
~__create_coupons.rb
class CreateCoupons < ActiveRecord::Migration[5.2]
  def change
    create_table :coupons do |t|
      t.integer :user_id
      t.boolean :is_valid, default: true # 「default: true」を追記
      t.integer :limit

      t.timestamps
    end
  end
end
단말기
$ rails db:migrate

2. 모델 편집


user.rb
# 追記
has_many :coupons, dependent: :destroy
coupon.rb
class Coupon < ApplicationRecord
  belongs_to :user

  enum is_valid: { '有効': true, '無効': false }

  def self.coupon_create(user)
    coupon = Coupon.new(user_id: user.id, limit: 1)
    coupon.save
  end

  def self.coupon_destroy
    time = Time.now
    coupons = Coupon.all
    coupons.each do |coupon|
      if coupon.created_at + coupon.limit.days < time && coupon.is_valid == '有効'
        coupon.is_valid = '無効'
        coupon.save
      end
    end
  end
end

[해설]


①enum으로 쿠폰의 상태를 관리한다.

enum is_valid: { '有効': true, '無効': false }

② 쿠폰을 만드는 방법을 정의한다.

def self.coupon_create(user)
  coupon = Coupon.new(user_id: user.id, limit: 1)
  coupon.save
end

③ 쿠폰을 삭제하는 방법을 정의한다.

def self.coupon_destroy
  time = Time.now
  coupons = Coupon.all
  coupons.each do |coupon|
    if coupon.created_at + coupon.limit.days < time && coupon.is_valid == '有効'
      coupon.is_valid = '無効'
      coupon.save
    end
  end
end
◇쿠폰 제작 24시간 후 쿠폰 상태가 유효하면 무효로 변경하고 저장한다.
if coupon.created_at + coupon.limit.minutes < time && coupon.is_valid == '有効'
  coupon.is_valid = '無効'
  coupon.save
end

3. coupons_controller.rb 만들기/편집


단말기
$ rails g controller coupons index
coupons_controller.rb
class CouponsController < ApplicationController
  def index
    @coupons = Coupon.where(user_id: current_user.id, is_valid: '有効') 
  end
end

4. books_controller.편집


이번에 책 투고에 성공하면 쿠폰을 발행하는 방식이 시행된다.
books_controller.rb
def create
  @book = Book.new(book_params)
  @book.user_id = current_user.id
  if @book.save
    Coupon.coupon_create(current_user) # 追記
    redirect_to books_path
  else
    @books = Book.all
    render 'index'
  end
end

5. 날짜 설정 변경


① application.편집


application.rb
module Bookers2Debug
  class Application < Rails::Application
    config.load_defaults 5.2
    config.time_zone = 'Tokyo' # 追記
  end
end

② 설정된 날짜와 시간 형식의 파일을 만들고 편집합니다.


단말기
$ touch config/initializers/time_formats.rb
time_formats.rb
Time::DATE_FORMATS[:datetime_jp] = '%Y/%m/%d/%H:%M'

6. 뷰 편집


coupons/index.html.slim
.row
  .col-xs-3

  .col-xs-6
    table.table
      thead
        tr
          th
            | クーポン番号
          th
            | タイトル

      tbody
        - @coupons.each.with_index(1) do |coupon, index|
          tr
            td
              = index
            td
              - limit = coupon.created_at + coupon.limit.minutes
              = limit.to_s(:datetime_jp)

  .col-xs-3

[해설]


① 쿠폰 제작 일자 이후 1일을 5로 설정한 형식으로 표시합니다.

- limit = coupon.created_at + coupon.limit.minutes
= limit.to_s(:datetime_jp)

7. 자동 제거 기능 설치


①Gem 도입


Gemfile
# 追記
gem 'whenever', require: false
단말기
$ bundle

②"schedule.rb" 제작, 편집


단말기
$ bundle exec wheneverize .
config/schedule.rb
env :PATH, ENV['PATH'] # 絶対パスから相対パス指定
set :output, 'log/cron.log' # ログの出力先ファイルを設定
set :environment, :development # 環境を設定

every 1.minute do
  runner 'Coupon.coupon_destroy'
end

4. cron 반영


단말기
$ bundle exec whenever --update-crontab

일괄 처리에서 자주 사용하는 명령

crontab -e ➡터미널에서cron 편집 준비$ bundle exec whenever ➡크론 설정 확인 준비$ bundle exec whenever --update-crontab ➡반응 준비 크론$ bundle exec whenever --clear-crontab ➡삭제 준비

좋은 웹페이지 즐겨찾기