find_or_create

November 12, 2009

Perhaps I’m missing something here, but here’s a method that I often add into my Rails models

def self.find_or_create opts
  first(:conditions => opts) || create(opts)
end

It’s use is simple:

 Membership.find_or_create :channel_id, :user_id

Now there is a dynamic finder self.find_or_create_by_XXX, but it isn’t useful in the same way.

Is there a reason why something like that method isn’t in AR core ?

One Response to “find_or_create”

  1. flunder Says:

    Ninja you saved me badly!

    My use:
    Collection.find_or_create_by_item_id_and_user_id(params[:collection])

    Thanks so much!


Leave a Reply