Search code examples
ruby-on-rails-3formtastic

Default value on select field in formtastic form with no model


I have a formtastic form to gather parameters for report generation. I know formtastic is designed to be used with models but I need to use it here as the form is in an activeadmin page.

It's all working well but I can't set a default value for the selects. I'm willing to implement a "despicable hack" to get this working. I'd prefer not to implement a fake model just to set default values on a form.

The form code looks like this

<%= semantic_form_for "report", :url => report_admin_payments_path do |f| %>
  <%= f.inputs do %>
    <%= f.input :report_type, :as => :select, :collection => report_types, :input_html => {:style => "width:180px"}  %>    
    <%= f.input :start_date, :as => :string, :input_html => {:class => 'datepicker', :style => "width:60px", :value => 1.month.ago.strftime("%Y-%m-%d")} %>
    <%= f.input :end_date, :as => :string, :input_html => {:class => 'datepicker', :style => "width:60px", :value => Time.zone.now.strftime("%Y-%m-%d")} %>
    <%= f.input :country, :as => :select, :collection => locales, :input_html => {:style => "width:180px"}%>
  <% end %>
  <%= f.actions :submit %>
<% end %>

Thanks in advance,

Matt


Solution

  • This or something similar should meet your needs.

    class LightModel
    
      # Subclass this for a model that looks like an ar model but has no persistence
      # good for formtastic forms
    
      include ActiveModel::Naming
      include ActiveModel::Validations
    
      def initialize(attributes = {})
        @attributes = attributes
      end  
    
      # read only atm
      def method_missing(m, *args, &block)
        @attributes[m]
      end  
    
    end
    

    Thanks,

    Matt