Reputation: 2900
In my app when user failed the Legal Test I should change their status to inactive
, current date to status_updated_at
and increment failed_attempts
. Normally I would user something like:
current_user.update!(
status: 'inactive',
failed_attempts: +1,
status_updated_at: Date.current
)
But is there a syntax to use built-in method like increment
to be current_user.update!( ... ,increment!(:failed_attempts)...),
?
I don't know but using counter_cache
is probably overkill since the User will have only 2 to 5 attempts.
Upvotes: 1
Views: 367
Reputation: 44581
There's a possibility of race condition (i.e. model instance is holding a stale value compared to the one in database), so one can use update_counters
with transaction
:
transaction do
current_user.class.update_counters(current_user.id, failed_attempts: 1)
current_user.update(status: :inactive, status_updated_at: Date.current)
end
Upvotes: 3
Reputation: 23859
I don't think it is a one shot possibility. You can try doing this:
current_user.increment(:failed_attempts)
current_user.update_attributes(status: 'inactive', status_updated_at: Date.current)
current_user.save!
or this:
current_user.update!(
status: 'inactive',
failed_attempts: (current_user.failed_attempts || 0) + 1,
status_updated_at: Date.current
)
Upvotes: 0