Forum: Ruby on Rails No Magic for HABTM forms?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Robert E. (Guest)
on 2006-02-20 22:04
(Received via mailing list)

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

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

class Person < ActiveRecord::Base
   has_and_belongs_to_many :registrations

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 =

     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 <<
         @registration.people << existing

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?


Bob E.
This topic is locked and can not be replied to.