02.01 購物網: 價格>0, 刪除功能, 彈出式視窗, 註冊為商家

目標

  • 新增商品時,價格與數量必須大於零
  • 商品頁面可以進行刪除商品
  • 註冊與登入是彈出式視窗
  • 註冊時可以選擇註冊為商家(Admin)

新增商品時,價格與數量必須大於零

只要改一個檔案
app/models/product.rb

product.rb
class Product < ApplicationRecord
  mount_uploader :image, ImageUploader
  validates :quantity, presence: true
  validates :price, presence: true
  validates :quantity, numericality: { greater_than: 0}
  validates :price, numericality: { greater_than: 0}

end

商品頁面可以進行刪除商品

只要改兩個檔案
app/controllers/admin/products_ _controller.rb

products_controller.rb
def destroy
    @product = Product.find(params[:id])
    @product.destroy
    flash[:alert] = "Product deleted"
    redirect_to admin_products_path
  end

app/views/admin/products/index.html.erb

index.html.erb
<%= link_to("Delete", admin_product_path(product), method: :delete, data: { confirm: "Are you sure?"} ) %>


有坑注意:controller 裡面是 admin_products_path, index.html 裡面是admin_product_path
前者的products有s, 後者沒有


在彈出式視窗進行註冊或登入

要改四個檔案,但是不怕,我們有教材
四個檔案是
app/assets/javascripts/application.js

//= require bootstrap/modal

app/views/common/_navbar.html.erb _
app/helpers/application_helper.rb
app/assets/stylesheets/application.scss

沒有教材的人也可以看我的Git hub


在註冊的時候可以選擇要註冊為商家

我參考這份學長的作業
我改了三個檔案
app/views/common/_ _navbar.html.erb

navbar.html.erb
  <div class="form-inputs">
                <%= f.input :email, required: true, autofocus: true %>
                <%= f.input :password, required: true, hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length) %>
                <%= f.input :password_confirmation, required: true %>
+               <%= f.input :is_admin, hint: ("如果你想申請成為商家,請勾選is_admin") %>
              </div>

app/controllers/users/registration_controller.rb

先rails g
rails g controller users/registration

registration_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
before_filter :configure_permitted_parameters

protected

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

第三個檔案,要記得改routes.rb,其實只改了第二行。

routes.rb
Rails.application.routes.draw do
  devise_for :users, :controllers => { :registrations => "users/registrations" }

  namespace :admin do
     resources :products
  end

  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root 'products#index'

  resources :products
end

Comments

comments powered by Disqus