Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to set a default value in a text_field?
    text
    copied!<p>I know this question has been asked a zillion times, but I still feel I'm missing something obvious. Given a model <code>Address</code> with a field <code>city</code> which we want to be initialized with a default value, say <code>Awesome City</code>.</p> <p>What I've tried so far:</p> <p>1) Default value in the view:</p> <pre><code># @file: /app/views/addresses/_form.html.erb &lt;dt&gt;&lt;%= f.label :city %&gt;&lt;/dt&gt; &lt;dd&gt;&lt;%= f.text_field :city, :value =&gt; 'Awesome city' %&gt;&lt;/dd&gt; </code></pre> <p>This works but doesn't feel right. Also the user cannot change it, the value will still be <code>Awesome city</code>.</p> <p>2) Overwriting the <code>city</code> method:</p> <pre><code># @file: app/models/address.rb def city self[:city] ||= 'Awesome city' end </code></pre> <p>The field is rendered empty, so for some reason it doesn't work. If you try <code>Address.new.city</code> you get the default value though.</p> <p>3) Assign the default value in the controller:</p> <pre><code># address doesn't have a controller, we use nested forms # belongs_to :parent # @file: /app/controllers/parents_controller.rb def new @parent = Parent.new @parent.build_address @parent.address.city = 'Awesome city' end </code></pre> <p>This actually works but I don't think it should be in the controller, rather in the model.</p> <p>4) Adding an <code>after_initialize</code> call (yes, it works, you don't have to overwrite the callback):</p> <pre><code># @file: app/models/address.rb after_initialize :set_default_city def set_default_city self.city = 'Awesome city' end </code></pre> <p>This works as well, but this will be called every time an object is instantiated as well, which we don't want.</p> <p>5) JavaScript, this seems like an extreme measure, it should be easier than this.</p> <p>Bottom line: what's the best way to add a default value? Everytime I have to give a field a default value it seems I'm trying to hard for such a simple thing. Are there other options which I'm missing?</p> <p><strong>Edit:</strong>: I'm using Rails 3.1.4 with Ruby 1.8.7/1.9.2</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload