Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Model.find_or_create_by_title - rails < 0.14 (See related posts)

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

Comments on this post

peter posts on Dec 14, 2005 at 18:51
Am I missing something? Rails added this functionality for free from 0.14. You can do find_or_create_by_FIELDNAME on any model now.

Also, you generally shouldn't set flash from a model.
mixonic posts on Dec 15, 2005 at 03:51
Haha, maybe yeah, I'll have to look for it. I was going through some old code and thought I'd share it. They did the same thing with outdating my autocompletion javascript setups :-p

Thanks peter.

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts