In that case I’d handle errors like this in the client-side level
besides the database level since I find it simpler, specially if
you’re using an OO approach with your models isolated from your
views.
In that case, if there is a bug in your client-side code that will
send duplicate entries to the server, in the worst case you’ll get a
500 response if you don’t handle it in the server.
Another approach if you want to handle this in the server-side would
be to do something like this:
begin
start_database_transaction
company = Company.create! params[:company] # simplified here, just
create the company with minimal params
# then add the partners to the company and ask to validate
company. Now the partners should have a valid company_id and the
built-in validations should work
...
unless company.valid?
handle_validation_error company.errors
raise 'duplicate entries'
end
...
rescue
rollback_database_transaction
end
Of course the suggestion above would only work with serious
databases (ie, not with the MyISAM engine in MySql, which is the
default for older versions of MySql).
In any case I'd suggest to release your gem first and then ask here
if the Rails core would be willing to include it by default in
ActiveRecord. In that case they would be able to look at the
documentation, source code and tests before making a decision.
But I'd like to tell you why I think lots of people are not using
nested params. If they’re like me the work-flow would look something
like this:
The user clicks in a Add Company button and would be asked the
company name. The application creates the company with no partners
associated.
Then the interface would add a button "Add partner" asking for the
partner data. In that case your actions would have to deal with a
single partner at once, making it easier to work with regular
validations and simplifying the logic too.
What I mean is that I find it quite easier to develop applications
using AJAX than trying to create complex forms that do lots of stuff
in a single request. Even testing such forms are painful in my
opinion. It is much easier to split the application in multiple
small parts that are easily testable separately.
Good luck with your decisions,
Rodrigo.