Mapping contained objects to forms?

I’m having lots of trouble trying to map an object that contains another
object to the right forms param. So say I have Book which has one
Publisher. Here is what I’ve tried:

Publisher
<%= text_field 'book', 'publisher.name' %>

Then

Publisher
<%= text_field 'book', 'publisher[name]' %>

And

Publisher
<%= text_field 'book.publisher', 'name' %>

All of them blow up with various exceptions. What is the right way to
map a many to one relationship onto a form? And how will it know the ID
of the contained object if it just has the name on the form? Is there
something else I have to do to put the Publisher’s ID on the form so I
can remember it? The Agile Web D. with Rails book is not
helpful on this issue.

Charlie

Bump. Any ideas? I’m sure someone knows how this works.

On 4/11/06, Charlie [email protected] wrote:

I’m having lots of trouble trying to map an object that contains another
object to the right forms param. So say I have Book which has one
Publisher. Here is what I’ve tried:

Publisher
<%= text_field 'book', 'publisher.name' %>

You cannot do the dotted method call with the standard Rails helpers
AFAIK. I got frustrated with not being about to do this so wrote a
helper for it (there are probably loads of better ways to achieve this
but it got me going). My ‘custom_text_field’ generates a text field
with a name of book[publisher][name] for your call.

I’m not entirely sure why this isn’t supported by Rails out-of-the-box.

Matt

class TagHelper
def custom_text_field(object_id, method, options = { })
text_field_tag(
object_field_name(object_id, method),
object_value(object_id, method),
options
)
end

def object_value(object_id, method)
method.split(“.”).inject(self.instance_variable_get(“@#{ object_id
}”)) { |o,m| o.nil? ? nil : o.send(m) }
end

def object_field_name(object_id, method)
method.split(“.”).inject(object_id) { |f,n| “#{ f }[#{ n }]” }
end
end