Why does activerecord save method throw an exception on violation of PK constraint instead of just returning false with an error message added to object.errors

69 views
Skip to first unread message

bwb

unread,
Nov 8, 2012, 11:27:40 AM11/8/12
to rails-sqlse...@googlegroups.com
In the following logic

if @official.save
...
else
...
end

the save method causes activerecord to throw an exception, instead of returning false with an error added to @official.errors; 

When I change to 

      begin
        @official.save
        redirect_to '/success.xml'
      rescue ActiveRecord::StatementInvalid => exception
       redirect_to '/failure.xml'
      end

the exception value is the full tiny_tds error string, as excerpted below:
(TinyTds::Error: Violation of PRIMARY KEY constraint 'PK_eo'. Cannot insert duplicate key in object 'dbo.eo'. The duplicate key value is (01001     , 1).: EXEC sp_executesql N'INSERT INTO [Eo] ([address1], [address2], [city], [createdate], [createuid], [dir_phone], [dir_phone_ext], [email], [eotypeID], [fax], [firstname], [jurisdictionID], 

etc.

Is there a way to have the save return false and have the key constraint violation message returned in an object errors attribute?

Thanks for any ideas.

 

Ken Collins

unread,
Nov 8, 2012, 1:28:09 PM11/8/12
to rails-sqlse...@googlegroups.com

Fix the root of the problem, your error. FWIW, you are never supposed to rescue StatementInvalid. I think it will mess up rollbacks, something in the AR docs say this.

- Ken

B.W. Basheer

unread,
Nov 8, 2012, 3:57:28 PM11/8/12
to rails-sqlse...@googlegroups.com


Did fix the problem, but will also remove the rescue.

Thanks, Ken.


Very truly,
Page Basheer
_____________________________
bwba...@retrievalsystems.com
www.retrievalsystems.com
B. William "Page" Basheer
President and General Counsel
Retrieval Systems Corporation
2071 Chain Bridge Road
Vienna, Virginia 22182
703-749-0012
703-749-0015 (fax)
202-288-4800 (Verizon cell)
--
You received this message because you are subscribed to the Google
Groups "Rails SQLServer Adapter" group.
To post to this group, send email to
rails-sqlse...@googlegroups.com.
To unsubscribe from this group, send email to
rails-sqlserver-a...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/rails-sqlserver-adapter?hl=en.

Reply all
Reply to author
Forward
0 new messages