How to set a default value for a select? #894

napster3000 opened this Issue Oct 30, 2012 · 3 comments


None yet
2 participants

form do |f|
f.inputs "Details" do
f.input :site
f.input :name
f.input :icon
f.input :country, :as => :select, :collection => {"USA" => "US", "United Kingdom" => "UK", "France" => "FR"}

How to say to "formastatic" that "UK" is the selected value?


justinfrench commented Oct 31, 2012

You initialize the model in your controller with the default values you want, and Formtastic will pre-select them in the view automatically (assuming that country is a string column where you're storing "UK":

def new
  @thing =[:thing]) ||= "UK"

This can be done in many ways, but the effect is the same. Set the default before rendering the form.

I would want to avoid edit my model to keep my code clean. Is there a way on views-side?


justinfrench commented Oct 31, 2012

@napster3000 no, this is the way to do it — set-up the model (either in the controller, or as part of model initialization) with the defaults and keep your views clean — that's the right place for this logic

We used to support this in the views as well, but

  1. it's the wrong place for this responsibility
  2. it was complicated for us to support and test
  3. it was impossible for use to consistently provide this support across all cases and types of inputs (see wiki

If you really want this back in, I suspect you could subclass SelectInput and hack it in pretty quickly, but I would resist this urge without a strong case against doing it in the model or controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment