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.

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.


You should use

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)

Need Your Help

WPF DataTemplate not throwing exception

wpf exception datatemplate

While designing a new WPF application I noticed exceptions not being thrown during data binding for controls with DataTemplates. To test I wrote the following simple user control with as little lo...

Does Bing 2.0 API support multiple queries in 1 request?

java web-services bing bing-api

Can I send more than 1 search request via JSON SourceType in a Bing 2.0 api call? I'm creating a custom library against Bing because I'm not on .NET.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.