On 4/11/06, Charlie <charlie.hubbard@gmail.com>
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