Let’s say I have a two models, Event and Person. An event has a coordinator that is a person:
class Event < ActiveRecord::Base
belongs_to :coordinator, :class_name => 'Person', :foreign_key => 'coordinator_id'
accepts_nested_attributes_for :coordinator
end
class Person < ActiveRecord::Base
validates :name, :length => 20
end
In my form, I would like to let the user pick from existing People objects (let’s say a list of radio buttons), but also have a text box to create a new Person (with the name entered in the text box).
How would I elegantly implement this? I can figure it out, but it involves a lot of ugly code in the Controller, and is a pain to validate.
I’ve done something similar in which the radio buttons set person[id] and then I just checked for the id.
So in my controller#create method:
You may have to delete the
idparam in theelseblock if the form sends it even if nothing is selected.Edit to answer validation question:
In the
#Handle saving @person here.is where you’d do what you normally do for creating an object. Like: