Forum: Ruby on Rails Mapping contained objects to forms?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Charlie (Guest)
on 2006-04-11 18:32
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:

<p><label for="book_publisher">Publisher</label><br/>
<%= text_field 'book', 'publisher.name' %> </p>

Then

<p><label for="book_publisher">Publisher</label><br/>
<%= text_field 'book', 'publisher[name]' %> </p>

And

<p><label for="book_publisher">Publisher</label><br/>
<%= text_field 'book.publisher', 'name' %> </p>

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
Charlie (Guest)
on 2006-04-12 03:57
Bump.  Any ideas?  I'm sure someone knows how this works.
Matthew D. (Guest)
on 2006-04-12 17:15
(Received via mailing list)
On 4/11/06, Charlie <removed_email_address@domain.invalid> 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:
>
> <p><label for="book_publisher">Publisher</label><br/>
> <%= text_field 'book', 'publisher.name' %> </p>

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
This topic is locked and can not be replied to.