-
-
Save rainly/874126 to your computer and use it in GitHub Desktop.
rails check_used for destroy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# customer.rb | |
before_destroy :check_used | |
def allow_destroy? | |
@allow_destory ||= LoadingBill.exists?(:author_id => self.id) | |
end | |
protected | |
def check_used | |
unless self.allow_destroy? | |
self.errors.add_to_base("此客户已经有提单了, 不能删除") | |
raise ActiveRecord::RecordInvalid.new(self) | |
end | |
end | |
# test_customer.rb | |
test "destroy a customer that has loading_bills" do | |
assert_raise(ActiveRecord::RecordInvalid) do | |
customers(:ibm).destroy | |
end | |
assert_match(/已经有提单/, customers(:ibm).errors.full_messages.to_s) | |
end | |
# test_customers_controller.rb | |
test "destroy success" do | |
customer = Customer.last | |
customer.loading_bills.delete_all | |
delete :destroy, :id => customer | |
assert_redirected_to customers_url | |
assert !Customer.exists?(customer.id) | |
end | |
test "destroy invalid" do | |
customer = Customer.last | |
assert_raise(ActiveRecord::RecordInvalid) do | |
delete :destroy, :id => customer | |
end | |
end | |
# 最在 index.html.erb | |
<%= link_to_if user.allow_destroy?, "删除", user, :confirm => "你确定删除吗?", :method => :delete %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment