Topic: polymorphic quandary

Maybe someone can help me. I'm relatively new to rails and can't figure this one out.
I've read the very good tutorials on using two models within a form.
Now, here's my situation:

I have lots of models. Most of them have an address associated with them. Instead of using 'city - state - zip' for each model, I set up a polymorphic association using an address model with the addressable id and type. This makes perfect sense not to duplicate columns in each model.

Now- on to my form (with two models for now). How can you save out two address fields within one form. Each going to the address model with the correct id and type.

Example:

My form has a dealership model that contains a city, state, zip.
In the same form, I have a bank model. That too needs to have fields for city, state, and zip.

My simple 'create' does the great job of updating the address model and assigning the addressable type and id as dealership correctly...but how can you save out banks also to the address model? So upon hitting create, two rows would be created with one being dealer type (with correct address), and the second address as bank type (with the banks address).

def create
    @dealership = Dealership.new(params[:dealership])
    @bank = @dealership.banks.build(params[:bank])
    @address = @dealership.addresses.build(params[:address])
    if @dealership.save
      flash[:notice] = 'Dealership was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

--------
thanks in advance.

Re: polymorphic quandary

This is quite a quandary. Fortunately there's a simple solution (I think anyway, haven't tested it).

You can keep the two addresses separate by simply giving them a different name. I don't mean actually changing the name of the model, just the variable/parameter name.

# in view
<%= text_field :dealership, :name %>
<%= text_field :dealership_address, :city %>
<%= text_field :bank, :name %>
<%= text_field :bank_address, :city %>

# in controller
def create
  @dealership = Dealership.new(params[:dealership])
  @bank = @dealership.banks.build(params[:bank])
  @dealership_address = @dealership.addresses.build(params[:dealership_address])
  @bank_address = @bank.addresses.build(params[:bank_address])
  #...
end


Does that work for you?

Railscasts - Free Ruby on Rails Screencasts

Re: polymorphic quandary

it works- fantastic!
and very simple.

Thanks a million.