Select an existing item or create a new one

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 :slight_smile:

It sounds like you are looking for something like ActiveRecord’s
find_or_create_by…() or find_or_initialize_by…() methods.

You might look into “Dynamic attribute-based finders” on
http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Thanks for your reply. Yeah I didn’t think that was suitable in this
case, with several fields, showing the user both options in the form
etc.

Anyway, I just figured out the issue…

I was using resource_controller and was trying to delete the nested
attributes (if not required) in a create.before… method. If I change
that to using a regular create method it works fine.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs