How to set a default value in a text_field?
ruby-on-rails, ruby-on-rails-3.1
Solution
You can define it in your migration file:
class CreateAddress < ActiveRecord::Migration
def change
create_table :addresses do |t|
...
t.string :city, default: "Awesome City"
...
t.timestamps
end
end
end
Other option is to define it in the `new` action, in your controller, which is more flexible... So, when you create a new `address` it will be started with the default value....
def new
@address = Address.new
@address.city ||= "Awesome City"
...
end
EDIT - possible solution to define default value in the model:
before_save :set_default_city
def set_default_city
self.city ||= 'Awesome city'
end
Problem
I know this question has been asked a zillion times, but I still feel I'm missing something obvious. Given a model `Address` with a field `city` which we want to be initialized with a default value, say `Awesome City`. What I've tried so far: 1) Default value in the view: ``` # @file: /app/views/addresses/_form.html.erb <dt><%= f.label :city %></dt> <dd><%= f.text_field :city, :value => 'Awesome city' %></dd> ``` This works but doesn't feel right. Also the user cannot change it, the value will still be `Awesome city`. 2) Overwriting the `city` method: ``` # @file: app/models/address.rb def city self[:city] ||= 'Awesome city' end ``` The field is rendered empty, so for some reason it doesn't work. If you try `Address.new.city` you get the default value though. 3) Assign the default value in the controller: ``` # 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 ``` This actually works but I don't think it should be in the controller, rather in the model. 4) Adding an `after_initialize` call (yes, it works, you don't have to overwrite the callback): ``` # @file: app/models/address.rb after_initialize :set_default_city def set_default_city self.city = 'Awesome city' end ``` This works as well, but this will be called every time an object is instantiated as well, which we don't want. 5) JavaScript, this seems like an extreme measure, it should be easier than this. 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? Edit:: I'm using Rails 3.1.4 with Ruby 1.8.7/1.9.2