RailsによるアジャイルWebアプリケーション開発
第9章 タスクD:カートの作成
before_destroyとbutton_toの使い方に注意。
- app/models/product.rb
class Product < ActiveRecord::Base validates :title, :description, :image_url, presence: true validates :price, numericality: { greater_than_or_equal_to: 0.01 } validates :title, uniqueness: true validates :image_url, allow_blank: true, format: { with: %r{\.(gif|jpg|png)\z}i, message: 'はGIF、JPG、PNG画像のURLでなければなりません' } has_many :list_items before_destroy :ensure_not_referenced_by_any_line_item private def ensure_not_referenced_by_any_line_item return true if line_items.empty? errors.add(:base, '品目が存在します') false end end
- app/views/store/index.html.haml
- if notice %p#notice= notice %h1 Pragmaticカタログ - @products.each do |product| .entry = image_tag(product.image_url) %h3= product.title = sanitize product.description .price_line %span.price= number_to_currency product.price = button_to 'カートに入れる', line_items_path(product_id: product)
- spec/controllers/line_items_spec.rb
require 'rails_helper' RSpec.describe LineItemsController, type: :controller do describe 'POST create' do let(:product) { create(:product) } it 'LineItem が登録されること' do expect { post :create, product_id: product }.to change(LineItem, :count).by(1) end it 'redirects to carts#show' do post :create, product_id: product expect(response).to redirect_to cart_path(assigns(:line_item).cart) end end end