I'm using Rails 3.2.8. I need to create a status record if a status record doesn't already exist. If a status record exists, I don't do anything. So my code is something like this:
user_level_status = UserLevelStatus.where(user_id: user_id, level_id: level_id).first
if !user_level_status
UserLevelStatus.create(user_id: user_id, level_id: level_id, status: UserLevelStatus::READY)
end
Is there a better way to handle this in Rails/ActiveRecord? Is there an equivalent mechanism as find_or_create_by_
? Can I use find_or_create_by_user_id
and also check for level_id
? I would just be discarding the results so even that's not so elegant.
Yes there is.
user_level_status = UserLevelStatus.find_or_create_by_user_id_and_level_id(user_id, level_id)
user_level_status = UserLevelStatus.find_or_create_by(user_id: user_id, level_id: level_id)
And you should set the default status
in your model.
You should use
UserLevelStatus.where(user_id: user_id, level_id: level_id).first_or_create(status: UserLevelStatus::READY)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With