Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create if doesn't exist function in ActiveRecord?

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.

like image 648
at. Avatar asked Sep 21 '12 09:09

at.


2 Answers

Yes there is.

Rails 3

user_level_status = UserLevelStatus.find_or_create_by_user_id_and_level_id(user_id, level_id)

Rails 4:

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.

like image 56
KARASZI István Avatar answered Sep 21 '22 19:09

KARASZI István


You should use

UserLevelStatus.where(user_id: user_id, level_id: level_id).first_or_create(status: UserLevelStatus::READY)
like image 30
iosctr Avatar answered Sep 17 '22 19:09

iosctr