Saturday, October 27, 2007

find or create by

So today I was working on a venture application I am trying to develop, when I cam across the need to only create a product if its not in the database. In this case I want to create the product only if the name of it is not in the database. While this is dangerous because of spelling but I am trying to keep it open for local (community) use. Slang terms may come up for one area so they need to be allowed. However I was having a difficult time looking at the pile of code for actually doing this.

 if Product.find_by_name("spotted cow")
product = Product.find_by_name("spotted cow")
else
product = Product.create(:name => "spotted cow")
end


So I found out about this method from someone in the rails chat on irc.freenode.net (there is always someone willing to help in that chat room.)

Product.find_or_create_by_name( params[:product][:name],
:category_id => params[:product][:category_id],
:for => 'creation' )

So now the product will be either found or created by the name of the product and if it is going to be created it adds the category_id just like a normal create.

Here is the test that proves this works.
  def test_find_or_create_by_name
assert Product.find_or_create_by_name("spotted cow",
:category_id => 1,
:for => :create)
assert Product.find_or_create_by_name("spotted cow",
:category_id => 1,
:for => :create)

assert Product.find_or_create_by_name("spotted cow",
:category_id => 1,
:for => :create)

assert Product.find_or_create_by_name("spotted cow",
:category_id => 1,
:for => :create)


products = Product.find_all_by_name("spotted cow")
assert_equal(1, products.length)
end


-CH

No comments: