Skip to content

Commit

Permalink
Show errors when has_many restrict_with_error.
Browse files Browse the repository at this point in the history
* Return full_messages with new line separator
  • Loading branch information
vgsantoniazzi committed Aug 10, 2017
1 parent 736266d commit 133f77a
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 5 deletions.
8 changes: 6 additions & 2 deletions app/controllers/administrate/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,12 @@ def update
end

def destroy
requested_resource.destroy
flash[:notice] = translate_with_resource("destroy.success")
if requested_resource.destroy
flash[:notice] = translate_with_resource("destroy.success")
else
flash[:error] = requested_resource.errors.
full_messages.join("<br/>").html_safe
end
redirect_to action: :index
end

Expand Down
2 changes: 1 addition & 1 deletion spec/example_app/app/models/order.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class Order < ActiveRecord::Base

validates :customer, presence: true
has_many :line_items, dependent: :destroy
has_many :payments, dependent: :destroy
has_many :payments, dependent: :restrict_with_error

validates :address_line_one, presence: true
validates :address_line_two, presence: true
Expand Down
11 changes: 11 additions & 0 deletions spec/features/orders_index_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,15 @@
t("administrate.controller.destroy.success", resource: "Order")
)
end

scenario "cannot delete because associated payment" do
create(:payment, order: create(:order))

visit admin_orders_path
click_on t("administrate.actions.destroy")

expect(page).to have_flash(
"Cannot delete record because dependent payments exist", type: :error
)
end
end
11 changes: 11 additions & 0 deletions spec/models/order_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@
expect(LineItem.all).to be_empty
end

it "raise error when try delete associated payment" do
order = create(:order)
create(:payment, order: order)

order.destroy

expect(order.errors[:base]).to eq(
["Cannot delete record because dependent payments exist"]
)
end

describe "#total_price" do
it "returns 0 when there are no line items" do
order = build(:order)
Expand Down
5 changes: 3 additions & 2 deletions spec/support/have_flash_matcher.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module Features
def have_flash(text)
have_css(".flash-notice", text: text)
def have_flash(text, options = {})
options.reverse_merge!(type: :notice)
have_css(".flash-#{options[:type]}", text: text)
end
end

0 comments on commit 133f77a

Please sign in to comment.