Reputation: 685
I would like to build a simple app where the user tracks how far he has run each day. I want it to be so that there is only one model entry per day. How do I limit the model to only allow one entry per day? I found a solution that suggests doing the following for a journal with unique daily journals:
add_index :journal_entries, [:user_id, :created_on], unique: true
However, I don't fully understand how to implement this. Do I have to have another model for this index?
Thank you!
Upvotes: 3
Views: 1340
Reputation: 8006
You probably want to do this from the controller, what I would recommend is when the user tries to enter an entry, you use first_or_create!
.
@entry = Entry.where(created_at: Time.now.beginning_of_day.utc..Time.now.end_of_day.utc).first_or_create!
@entry.update_attributes(entry_params)
The above code finds an entry created within the current date, or creates one if it does not exist.
Upvotes: 4