Search code examples
ruby-on-railsrubyruby-on-rails-3formsformtastic

Formtastic make the correct fields on the fly?


I am using Formtastic and also using the accepts_nested_attributes_for ..here are models

class Tournament < ActiveRecord::Base
  has_many  :courts, :dependent => :destroy
  accepts_nested_attributes_for :courts, :allow_destroy => true

class Court < ActiveRecord::Base
  belongs_to :tournament

I need to have a form that one of the questions in the tournament form will determine how many courts i need to build. Here is my approach now

def new
  @tournament = Tournament.new
  25.times do
    @tournament.courts.build
  end

and in the view

<%= semantic_form_for @tournament do |f| %>
  <%= f.inputs do %>
    <%= f.input :number_courts, :hint => "How many courts are available?" %>
        <%= f.semantic_fields_for :courts do |ct| %>
          <%= ct.input :name %>
        <% end %>

the problem with this approach is that I will always prompt the user with 25 fields when really i need only the amount they enter from the question "How many courts are available?"

Is there a way to do this or just add them with a link ...any ideas


Solution

  • There are certainly more than one ways to do this. Here is one.

    Have the 25 courts prebuilt in the new action and include them in the new page but do not display them (display:none). On the client side when the user enters/selects the number of courts then you display those number of court input fields. You will need very simple javascript for this. On the rais controller side you can ignore all the court fields that are beyond the number of courts selected by the user

    In your params the court fields would come in an as array. Use slice! to get rid of the extra courts.

    params[:tournament][:courts].slice!(0..params[:tournament][:number_courts].to_i)