LoginSignup
6
16

More than 3 years have passed since last update.

[rails]ECサイトでのカートの作り方(カートモデル持たない版)

Last updated at Posted at 2020-04-22

カートモデルを作らずにカート機能を作れたので、貼っておきます。
ネット上にあまり記事がなかったので、、、

cart_items_controller
def create
    @cart_item = current_user.cart_items.build(cart_item_params)
    @cart_item.save
end

思いの外、シンプルになりました。
ここから、商品詳細のviewで必要なキーを代入していきます。

items/show.html.erb

    <%= form_for(@cart_item) do |f| %>
      <% if user_signed_in? %>
        <%= f.hidden_field :user_id, :value => current_user.id %>
      <% end %>
    <% end %>

まずは、ログインしているユーザーのPKをカートの商品のFKに入れてあげましょう。
買い物で言うと、棚から商品とって「これ、自分の番号書いとこ」みたいなイメージですかね。
ここでif文にしないと、ログインしていないユーザーが商品詳細ページに行けないので注意。

items/show.html.erb

    <%= form_for(@cart_item) do |f| %>
      <% if user_signed_in? %>
        <%= f.hidden_field :user_id, :value => current_user.id %>
      <% end %>                                  Item.find(params[:id])
        <%= f.hidden_field :item_id, :value => @item.id %>
        <%= f.submit "カートに入れる", class: "btn btn-primary" %>
    <% end %>

あとは、商品側もキーを代入してあげましょう。
カートに入ってる商品見て、「てか、これどこの棚にあったん?棚の番号もふっとこか。」みたいな感じですかね。すいません。
hidden_fieldでキーを代入すると、シンプルになりますね。ちょっと感動しました。

参考までに↓

schema.rb

create_table "cart_items", force: :cascade do |t|
    t.integer "item_id"
    t.integer "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
6
16
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
6
16