diff options
author | Gareth Rees <gareth@mysociety.org> | 2014-04-14 12:02:48 +0100 |
---|---|---|
committer | Gareth Rees <gareth@mysociety.org> | 2014-04-14 14:13:51 +0100 |
commit | 97075669802ec9e99bbcb5b52f539b3e3bbf2487 (patch) | |
tree | ed4b03dbf38224d10ab1f2bd2edd6e971282546d | |
parent | f1fd69bff059cf0dbd4c0e543dbd9d9079ea3be8 (diff) |
Handle validation errors in PublicBody.import_csv
Specifically using save! so that anything other than an
ActiveRecord::RecordInvalid doesn't get missed
Note that ActiveModel::Errors#full_messages includes the attribute key
in the message. This is by design, so we should consider whether we can
improve the way that we use translated validation messages.
-rw-r--r-- | app/models/public_body.rb | 10 | ||||
-rw-r--r-- | spec/models/public_body_spec.rb | 13 |
2 files changed, 22 insertions, 1 deletions
diff --git a/app/models/public_body.rb b/app/models/public_body.rb index 4aaca8337..9cb344f14 100644 --- a/app/models/public_body.rb +++ b/app/models/public_body.rb @@ -506,7 +506,15 @@ class PublicBody < ActiveRecord::Base public_body.publication_scheme = public_body.publication_scheme || "" public_body.last_edit_editor = editor public_body.last_edit_comment = 'Created from spreadsheet' - public_body.save! + + begin + public_body.save! + rescue ActiveRecord::RecordInvalid + public_body.errors.full_messages.each do |msg| + errors.push "error: line #{ line }: #{ msg } for authority '#{ name }'" + end + next + end end end end diff --git a/spec/models/public_body_spec.rb b/spec/models/public_body_spec.rb index c443f0d6a..38e31783d 100644 --- a/spec/models/public_body_spec.rb +++ b/spec/models/public_body_spec.rb @@ -533,6 +533,19 @@ describe PublicBody, " when loading CSV files" do PublicBody.count.should == original_count + 3 end + it "should handle active record validation errors" do + csv = <<-CSV +#name,request_email,short_name +Foobar,a@example.com,foobar +Foobar Test,b@example.com,foobar +CSV + + csv_contents = normalize_string_to_utf8(csv) + errors, notes = PublicBody.import_csv(csv_contents, '', 'replace', true, 'someadmin') # true means dry run + + errors.should include("error: line 3: Url name URL name is already taken for authority 'Foobar Test'") + end + end describe PublicBody do |