I have a form that manages a few models, using
accepts_nested_attributes_for

The new event form passes params like so:
"event"=>{
   "name"=>"",
   "happenings_attributes"=>{
     "0"=>{
       "location_attributes"=>{
         "city"=>"",
         "country"=>"",
         "state"=>""
        },
        "location_id"=>"26"}
    }
 }

It all works fine, except I'd like to add a choice of selecting an
existing location, or entering values for a new one to be created.

I might be going brain dead - I imagine this is a common thing to do -
like selecting an existing address or creating new one on an e-
commerce site, but alas I've never done it and can't seem to find
relevant search results.


Things I've tried:
-----------------------
# option 1: remove the location_attributes at the controller level, if
an existing location_id is passed

If so, this is the snippet of code I'm using in a before_filter on the
create action:
 params[:event][:happenings_attributes].each do |h|
   unless h[1]["location_id"].blank?
     h[1].delete("location_attributes")
   end
 end

- which goes ignored and the validations for creating a new location
are triggered.



I got to the h[1] level by playing around in console like so:
 params = {
  "event"=>{
    "name"=>"",
    "happenings_attributes"=>{
      "0"=>{
        "start_at" => '2010-03-02',
        "location_attributes"=>{
          "city"=>"",
          "country"=>"",
          "state"=>""
         },
         "location_id"=>"26"}
     }
  }
 }
 >> params['event']['happenings_attributes'].each do |h|
 ?> puts h.class
 >> end
 Array
 => {"0"=>{"location_attributes"=>{"city"=>"", "country"=>"",
"state"=>""}, "start_at"=>"2010-03-02", "location_id"=>"26"}}
 >> params['event']['happenings_attributes'].each do |h|
 ?> puts h[1]["location_id"]
 >> puts h[1]["location_attributes"]
 >> end
 26
 citycountrystate


 --------------------

 # option 2: remove the location_attributes at the model level

 # Happening model
 before_validation :check_new_or_existing_location

 def check_new_or_existing_location
   if !location_id.blank?
     location_attributes= nil
   end
 end

  --------------------


 Any suggestions appreciated :)

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to