Step.10 寫一支機器人塞亂數產品進去 - Azraeil/JCcart_Note GitHub Wiki

裝新的gem faker

add gem "faker" to Gemfile,然後bundle install再重開rails s。

接著我們去faker GitHub,這是一個塞假資料的gem,JC後來是使用Faker::Address.state

先進入console

rails c

:001 > Faker
:002 > Item.count
:003 > Item
:004 > 100.times do |i|
:005 >     Item.create(:name => Faker::Address.state, :price => rand(1..3000))
:006?>   end;
:007 >   true

然後發現噴了,查看錯誤訊息,是因為少了default的cate_id

ActiveRecord::StatementInvalid: Mysql2::Error: Field 'cate_id' doesn't have a default value:
            INSERT INTO `items` (`name`, `price`, `created_at`, `updated_at`)
            VALUES ('Virginia', 2474, '2016-09-09 08:45:00', '2016-09-09 08:45:00')

所以我們再繼續

:008 >   100.times do |i|
:009 >     Item.create(:name => Faker::Address.state, :price => rand(1..3000), :cate => cate)
:010?>   end; true

就能成功生假資料,接著再去重整localhost:3000/dashboard/admin/items就能看到100筆資料,然後我們隨便拿一筆資料按編輯,然後發現他又噴Template is missing

fix admin/items_controller

fix app/controllers/dashboard/admin/items_controller.rb

class Dashboard::Admin::ItemsController < Dashboard::Admin::AdminController
  def index
    @items = @paginate = Item.order('id DESC').paginate(:page => params[:page])
  end

  def new
    @item = Item.new
  end

  def edit
    @item = Item.find(params[:id])
  end

  def create
    @item = Item.new(item_params)
    @item.save
    redirect_to action: :index #這是舊版寫法
    #新版寫法  redirect_to dashboard_admin_items_path
  end

  def update
    @item.update(item_params)
    redirect_to action: :index
  end

  def destroy
    @item.destroy
    redirect_to action: :index
  end
end

private

def item_params
  params.require(:item).permit!
end

通常後台會倒序排序,所以會寫Item.order('id DESC').paginate(:page => params[:page])

接著再按編輯,發現又噴了,查看錯誤訊息,是先前index.html.erb的route寫錯

fix admin/items/index.html.erb

fix app/views/dashboard/admin/items/index.html.erb

原本是

<%= link_to '編輯', edit_item_path(item) %>

查看route,應該是要走到dashboard/admin/items#edit,查看Prifx應該是edit_dashboard_admin_item,所以我們改成

<%= link_to '編輯', edit_dashboard_admin_item_path(item) %>

delete原本的路由也是錯的,改成

<%= link_to '刪除', dashboard_admin_item_path(item), method: :delete, data: { confirm: '你確定嗎?' } %>

fix admin/items/edit.html.erb

重整頁面再按一次編輯,然後又噴了,錯誤訊息是寫form_for有問題,所以辜狗去查rails api form_for

這邊都會把form_for怎麼用講得很清楚,我們去看form_for傳的url參數,發現是傳:url,所以我們回去改

fix app/views/dashboard/admin/items/edit.html.erb

<%= form_for @item, :url => dashboard_admin_item_path, method: :patch  do |f| %>
  ...
  ...
<% end %>

接著再重整頁面,然後按編輯,終於能work了

fix dashboard/admin/items_controller

接著,我們隨便找一個來編輯,改掉價格後送出,又噴undefined method "update" for nil:NilClass,是因為我們在controller的upeate action沒有宣告@item

fix app/controllers/dashboard/admin/items_controller.rb

def update
  @item = Item.find(params[:id])
  ...
end

眼角餘光掃到destroy action也沒有,一樣加上@item = Item.find(params[:id])

⚠️ **GitHub.com Fallback** ⚠️