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

Friday, October 26, 2007

CVNUG (Chippewa Valley .Net User Group)

Last night I was able to explain the basics of Ruby on Rails to the .Net group that I belong to. It was really a great experience and was greatly received by the group. I was nervous about the response I would get initially from the group as some members of the Rails community come across as arrogant bastards.

The presentation when off with out a hitch thanks to the help of Brian Hogan (http://www.napcs.com/) who was there to answer questions and explain information more in depth as I demonstrated building a "Cookbook" application. I stripped down a version of Brian's cookbook tutorial and turned it in to a demonstration.

I want to give a shout out to CVNUG (http://cvnug.wi-ineta.org/) for letting me present to them the wonders of working with Rails. I would also like to thank Brian for helping me out with the presentation.

-CH

Tuesday, October 23, 2007

Connecting to ms SQL from OS X

This one got me again today as I usually do not use SQL Server for my rails apps.  I was having a hard time remembering the steps for updating my odbc connector for SQL server.  Brian Hogan over at New Auburn Personal Computer Services has a great post on how to do this so check it out here: 
http://www.napcsweb.com/blog/2007/03/08/15/#more-15