The output I get is the text of the ‘location’ rendering correctly, and
then an empty text input box! If the text can render then I must have
an object, so why doesn’t the text_field create the text input box?
On Thu, Feb 23, 2006 at 05:47:48PM +0100, Adam wrote:
Hi I’m having a problem with a little code here, hopefully it’s easy to
see what’s happening:
<% @lectures.each do |lecture| %>
<%= lecture.location%>
<%= text_field ‘lecture’, ‘location’ %>
<% end %>
Take a look at the rendered HTML and I believe you’ll find
the following:
value="#{@lecture.location}"
In other words it is looking for an instance variable named
lecture in the current object. In your case lecture is
a variable defined in the scope of the iterator.
One way around it (and I’m pretty sure this isn’t the best
practices solution) would be to define a partial and do
something like the following:
Okay I know it is bad form to reply to myself but just to clarify
what I was saying… The first argument to text_field is expected
to be an instance variable of the current object. Here’s an
example:
% script/console
Loading development environment.
include ActionView::Helpers::FormHelper
=> Object
class Lecture
attr :loc
def initialize(l) @loc = l
end
end
=> nil
Notice in the first call to text_field @foo was used and not the
local variable foo. In the second call @bar is nil so text_field
simply leaves off the ‘value=…’ part.
If you look at the HTML rendered by your code:
<% @lectures.each do |lecture| %>
<%= lecture.location%>
<%= text_field ‘lecture’, ‘location’ %>
<% end %>
I believe you will find that the value attribute of the input field
is missing because @lecture is nil. Hope that clears things up.
No its a little inconsistency in the rails api there. The string
that you pass for the object into the form field helper needs to be
‘foo’ and the instance var it references needs to be @foo. It is just
the way it is. I’m not defending it But thats the current state of
affairs.