Note that there are some explanatory texts on larger screens.

plurals
  1. PORails custom validation checking for duplicates
    text
    copied!<p>A table has following fields: badge_id, output_id, timely, removed, updated_at. For each badge_id, there can't have two valid records with the same output_id. But it doesn't mean that (badge_id, output_id) is a unique combination. Removed column indicates the current row has been removed or not. Basically delete or update operation triggers inserting a new row in the table with the latest change. So for example, we have a record like this:</p> <pre><code>badge_id| output_id| removed| timely | updated_at 1 | 1 | N | Y | 2013-11-26 </code></pre> <p>To remove that record, we actually insert another row and now it reads like</p> <pre><code>badge_id| output_id| removed| timely | updated_at 1 | 1 | N | Y | 2013-11-26 1 | 1 | Y | Y | 2013-11-27 </code></pre> <p>Because the latest record of (badge_id: 1, output_id: 1) has removed column set, it means that combination has been deleted. But I can't have two rows of same (badge_id: 1, output_id: 1), both have removed as "N" like:</p> <pre><code>badge_id| output_id| removed| timely | updated_at 1 | 1 | N | N | 2013-11-26 1 | 1 | N | Y | 2013-11-27 </code></pre> <p>So every time to add a new output_id for a certain badge_id, I have to check for duplication. But usual validates uniqueness of (badge_id, output_id) from ActiveModel doesn't work here. How do I write a clean custom validation for this? Thanks.</p> <p><strong>UPDATE:</strong></p> <p>I think I might have missed some key points. A record can be added and then deleted and then added repeatedly. So a combination of (badge_id, output_id, removed) isn't unique either. When add a new record, we need to check for (badge_id, output_id), whether <strong>latest</strong> record has removed set as 'Y' or not. </p> <p>So for possible answer like </p> <pre><code>validate_uniqueness_of :badge_id, scope: [:output_id], conditions: -&gt; { where(removed: "N") } </code></pre> <p>At the condition where clause, it should have order by updated_at desc and the first one has removed: 'N'. How do I fit that kind of condition into this one line code? Or there's a better way of doing this?</p>
 

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