Forum: Ruby on Rails default value in text field

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.
ss (Guest)
on 2006-05-12 17:10
hi,

This should be really simple, but i cant seem to find the answer
anywhere!!

In my _form.rhtml I have the following text field, how can I define a
default value?
<%= text_field 'purchaseorder', 'number'  %>
Bryan D. (Guest)
on 2006-05-12 17:24
Back in your controller action, do:

def new
@purchaseorder.number = "some number"
end
Mike G. (Guest)
on 2006-05-12 17:29
(Received via mailing list)
<%= text_field 'purchaseorder', 'number', :value => "some value" %>

but like Bryan said, if you have an instance variable named
purchaseorder, rails should automatically fill in the default value
with the attributes of this variable.

Mike
ss (Guest)
on 2006-05-12 17:33
Bryan D. wrote:
> Back in your controller action, do:
>
> def new
> @purchaseorder.number = "some number"
> end

thanks :)
Jonathan V. (Guest)
on 2006-05-13 07:05
(Received via mailing list)
Possibly a better way to accomplish this is to set a default on the
model object when it is instantiated:

class PurchaseOrder < ActiveRecord::Base
  def initialize(attributes = nil)
    super
    self.number = 123 unless number?
  end
end

-Jonathan.
This topic is locked and can not be replied to.