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:
Post a Comment