Reputation:
Business logic: A user can only create one entry for a journal per day. Before an entry can be created, it must query the records to determine if an entry has already been created for today.
I was looking for advice on the best way to approach this. I had a few ideas how to implement it on the client-side, but I'd really like to have validation on the model layer instead. Any help would be appreciated.
Upvotes: 6
Views: 1885
Reputation: 10693
Create a unique index on the journal table:
add_index :journal_entries, [:user_id, :created_on], unique: true
Then only one record with given user_id and date can be created and the database will raise an exception if this is violated. Note that created_on
must be a date
column, not datetime
.
This is the only way to make it 100% sure that you don't get duplicates without explicit exclusive lock on the table.
Upvotes: 7