form for

Wait! It's my understanding that "form_start_tag" and "form_end_tag" are deprecated. The use of "form_tag" is still perfectly fine for non- model related forms.

Please correct me if I wrong on this.

monki wrote:

Here is what I have done in that situation. in the form you will want:   <%= f.text_field :country %>

Then inside your tenant model:   def country=(country)     self.country = Country.find_by_name(country)   end

Would the country method be an endless loop, where self.country = Country.find_by_name(country) would call the country method again...and again...and again?

Which would inevitably cause a stack overflow.

Still new to Ruby that that seems logical.

SystemStackError: stack level too deep: SELECT * FROM countries WHERE (countries.`name` IS NULL) LIMIT 1

self.country = anything is going to recursively call your new definition of country=.

Try

  self[:country_id] = Country.find_by_name(country).id rescue nil

instead.

(The rescue part is in case find_by_name fails and it ends up calling nil.id)

Jeff softiesonrails.com

oops.

Yeah, I gave myself this error too.

UG...

I fought with that earlier.

What I proposed should work, but you'll want to name the country field something else on the form (something different from what the actual field is called in the database).

So you should be able to get it to work like this: in the form you will want:   <%= f.text_field :country_name %>

Then inside your tenant model:   def country_name=(country_name)     self.country = Country.find_by_name(country_name)   end

That way you get the effect you want and don't get the loop. Sorry about the confusion. The infinite loop there is tricky bits.

The: def something=(something) will only work if there is a field on the form named 'something'. Since there isn't one named 'street, number, unit' that function wouldn't get called at all.

You could do this like the following. For each of the street, number, and unit fields: First, add a street name field to your form. Then, in the model: def street_name=(street_name)   @street_name = street_name end

After you assign all three values you are ready to do the lookup (the instance variables won't get saved, so you need to put them into a field that will). So, in your model use a callback after the save (when all the instance variables would be assigned):

after_save :find_address def find_address   self[:address_id] = Address.find(:first, :conditions["street = ? AND number = ? AND unit = ?", @street, @number, @unit]).id rescue nil end

I think that will get you what you were after.