0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

link_toについて(編集中)

Posted at
index.html.erb
<% @cart_items.each do |cart_item| %>

<%= link_to "削除する", cart_item_path(cart_item), 
    method: :delete, data: { confirm: "本当に削除しますか?" },
    class: "btn btn-danger" %>

<% end %>

link_toメソッドに渡している2つ目の引数のcart_item_path(cart_item)というのもメソッドで、/cart_items/1のような指定したURLを表す文字列を返してくれます。cart_item_pathというメソッド名はどこからやってくるかというと、routes.rbで登録したルーティングのニックネーム(asで書いたやつ)+_pathという構造になっています。メソッドをどこかで定義するわけではなく、Railsがroutes.rbを読み、自動的に作ってくれる。
  cart_item_pathメソッドへ(cart_item)を渡すことで、自動的にidを取り出し、/cart_item/1のようなURLを作ってくれます。とりあえず、link_toでaタグを作るのだな〜とぼんやり理解で問題ありません。

ここを cart_item"s"_path(cart_item)と複数形にしてしまうと、 URLが /cart_items.1 になってしまうので注意!!

routes.rb
  scope module: 'publics' do
    # カート内商品について
    resources :cart_items, only: [:index, :update, :create, :destroy] do
      delete 'destroy_all', on: :collection    
    end
  end

作成されたものは以下になる

destroy_all_cart_items DELETE /cart_items/destroy_all(.:format) publics/cart_items#destroy_all
cart_items GET /cart_items(.:format) publics/cart_items#index
POST /cart_items(.:format) publics/cart_items#create
cart_item PATCH /cart_items/:id(.:format) publics/cart_items#update
PUT /cart_items/:id(.:format) publics/cart_items#update
DELETE /cart_items/:id(.:format) publics/cart_items#destroy

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?