Topic: How do I compare to tables?

I did a search and I also tried to search the Agile Rails book but maybe I wasn't using the right words, but how do I compare tables?

I've got a table with a list of cities and their respective states already filled out called "cities".  Then when someone fills out, what would go to the "addresses" table, I want it to first check with the "cities" table to see if it's a valid city/state.  If so it will let them save.  If not it will do a flash notice to tell them to check their spelling or whatever.  Or could I just have the textbox autocomplete from the "cities" table, but save to the "addresses" table?   

Thanks as always.

Re: How do I compare to tables?

I'm assuming you have a City model set up? Then you can do a find for a given city like this:

city = City.find(:first, :conditions => ['name = ?', city_name])
if city.nil?
  # no city was found with city_name
else
  # city was found!
end

There's actually an easier way to perform the find since the conditions are so simple

city = City.find_by_name(city_name)

Instead of duplicating the city name in the addresses table, you may want to set up an association. You can do this by adding a "city_id" column to the addresses table and doing this:

class Address < ActiveRecord::Base
  belongs_to :city
end

class City < ActiveRecord::Base
  has_many :addresses
end


Yes, it is possible to do an auto-complete on city names, but you may want to start another topic for that.

Railscasts - Free Ruby on Rails Screencasts

Re: How do I compare to tables?

That makes perfect sense for the tables. 

I've actually gotten autocomplete to work thanks to script.aculo.us, but I don't really understand how to set up or what the options part is.  Unless it's a quick answer I'll try and read more about it before asking. 

Thanks