No Magic for HABTM forms?


#1

Hi,

I posted yesterday asking how to get form tags to reference the
associated objects in a habtm relationship. I was hoping for Rails
Magic, but it looks like Rails doesn’t have habtm magic beyond a
certain point.

Here was my solution for others who might have the problem. Also, I
hope someone shows me that there is a simpler way.

The Database Model:

class Registration < ActiveRecord::Base
has_and_belongs_to_many :people
has_and_belongs_to_many :scheduled_courses
end

class ScheduledCourse < ActiveRecord::Base
belongs_to :course
belongs_to :teacher
has_many :course_dates
belongs_to :location
has_and_belongs_to_many :registrations
end

class Person < ActiveRecord::Base
has_and_belongs_to_many :registrations
end

What I needed was to have one registration form web page that a user
fills out to register for a scheduled_course. The courses will have
TWO attendees, so the form has entry fields for two people. I wanted
the controller to be able to create those two people automatically
when it got the form submission. It seemed like the variable names in
the form could support that with [] names, for example,

text_field(“registration[people_ids][]”, “first_name” …

But it seems it can’t do that, so I used text_field_tag in the form
like so:

text_field_tag(“registration[people][1][first_name]” …
text_field_tag(“registration[people][2][first_name]” …

Then my registration_controller handles the creation and mapping of
those two people to the registration explicitly (This feels LAME):

def save_registration
reg_params = @params[‘registration’]
@registration = Registration.new()

 people = reg_params[:people]
 people.each {|key, properties|
   existing = Person.find(:first, :conditions => ["first_name = ?

AND last_name = ?", properties[“first_name”], properties[“last_name”]])
if existing.nil?
@registration.people << Person.new(properties)
else
@registration.people << existing
end
}
if @registration.save

end

I haven’t dealt with re-displaying the form in case of errors yet,
but I hope that the params in the request will map faithfully back to
the form fields. I am not sure though. Surely, I am missing
something. Any help?

Thanks,

Bob E.