diff --git a/app/controllers/admin/lunchboxes_controller.rb b/app/controllers/admin/lunchboxes_controller.rb index 9b3403b..7e792c7 100644 --- a/app/controllers/admin/lunchboxes_controller.rb +++ b/app/controllers/admin/lunchboxes_controller.rb @@ -32,10 +32,14 @@ def create # PATCH/PUT /lunchboxes/1 def update + if @lunchbox.update(lunchbox_params) redirect_to admin_lunchboxes_path, notice: 'Lunchbox was successfully updated.' else - render :edit + puts("#########") + puts("#########") + puts("#########") + render :edit, notice: '更新できませんでした' end end diff --git a/app/models/lunchbox.rb b/app/models/lunchbox.rb index 4a28630..2de43c0 100644 --- a/app/models/lunchbox.rb +++ b/app/models/lunchbox.rb @@ -10,4 +10,27 @@ # class Lunchbox < ApplicationRecord + has_many :order_items + has_many :orders, through: :order_items + + # validation + + validate :prevent_future_reserved_lunchbox, on: :update + + private + def prevent_future_reserved_lunchbox + # 弁当に紐づくオーダーを取ってくる + # 未来日のオーダーに自分が含まれているかを確認 + # 含まれている場合は更新させない + # puts orders.where("date > ?", Date.current).present? + # puts orders.first.date + # puts self.name + # puts Date.current + # puts"###################" + + if orders.where("date > ?", Date.current).present? + errors.add(:future_date, "未来日に予約された弁当は更新できません") + end + end + end diff --git a/spec/features/admin/prevent_update_future_reserved_lunchbox_spec.rb b/spec/features/admin/prevent_update_future_reserved_lunchbox_spec.rb new file mode 100644 index 0000000..6cd16a8 --- /dev/null +++ b/spec/features/admin/prevent_update_future_reserved_lunchbox_spec.rb @@ -0,0 +1,21 @@ +require 'rails_helper' + +RSpec.feature '未来日に予約されている弁当の更新を行う時にエラーにする', type: :feature do + given!(:order) { create(:order, date: Time.zone.local(2017, 2, 4)) } + given!(:lunchbox) { create(:lunchbox) } + + scenario '未来日に予約を入れた状態で、その弁当を更新する' do + Timecop.freeze(Time.zone.local(2017, 2, 1)) do + create(:order_item, lunchbox_id: lunchbox.id, order: order) + + visit edit_admin_lunchbox_path(lunchbox) + + fill_in 'Name', with: "new_lunchbox_name" + + click_button('Update Lunchbox') + + expect(page).to have_text('未来日に予約された弁当は更新できません') + # expect(page).not_to have_text('new_lunchbox_name') + end + end +end