Model.find_or_create_by_title - Rails < 0.14
Join the DZone community and get the full member experience.Join For Free
Check it! In our model for rails we can have a need to get the id for a title, but sometimes want to create the title on the fly (like adding a tag to something, if it's there we want the id, if it's not we want to make it and get back the id). That'd be messy in the controller, this is much nicer: *Note - only for < 0.14 rails. Something like this became standard in rails after that.
def Project.find_or_create_by_title(title) return nil if title.empty? if (project = Project.find( :first, :conditions => [ 'title = ?', title ] )) return project.id else project = Project.new project.title = title if project.save return project.id else @flash[:notice] = 'Sorry, a project could not be created' return nil end end end
Opinions expressed by DZone contributors are their own.