Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Parsing the error message is not so bad, but feels kludgy. A suggestion I ran across (don't remember where) that seems appealing is that in the rescue block you can check the database to see if there is in fact a duplicate record. If there is, then chances are the StatementInvalid is because of the duplicate and you can handle it accordingly. If there isn't, then the StatementInvalid must be from something else, and you must handle it differently.</p> <p>So the basic idea, assuming a unique index on <code>recipe.name</code> as above:</p> <pre><code>begin recipe.save! rescue ActiveRecord::StatementInvalid if Recipe.count(:conditions =&gt; {:name =&gt; recipe.name}) &gt; 0 # It's a duplicate else # Not a duplicate; something else went wrong end end </code></pre> <p>I attempted to automate this checking with the following:</p> <pre><code>class ActiveRecord::Base def violates_unique_index?(opts={}) raise unless connection unique_indexes = connection.indexes(self.class.table_name).select{|i|i.unique} unique_indexes.each do |ui| conditions = {} ui.columns.each do |col| conditions[col] = send(col) end next if conditions.values.any?{|c|c.nil?} and !opts[:unique_includes_nil] return true if self.class.count(:conditions =&gt; conditions) &gt; 0 end return false end end </code></pre> <p>So now you should be able to use <code>generic_record.violates_unique_index?</code> in your rescue block to decide how to handle StatementInvalid.</p> <p>Hope that is helpful! Other approaches?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload