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 .
你应该用
UserLevelStatus.where(user_id: user_id, level_id: level_id).first_or_create(status: UserLevelStatus::READY)
Use find_or_create_*
hash = {user_id: user_id, level_id: level_id, status: UserLevelStatus::READY}
UserLevelStatus.find_or_create_by_user_id_and_level_id_and_status(hash)
EDITED For your case you should use following
hash = {user_id: user_id, level_id: level_id}
UserLevelStatus.find(:first, :conditions => hash) || UserLevelStatus.create(hash.merge({status: UserLevelStatus::READY})
Another alternative is
UserLevelStatus.where(user_id: user_id, level_id: level_id).first ||
UserLevelStatus.create(user_id: user_id, level_id: level_id, status: UserLevelStatus::READY)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.