Search code examples
ruby-on-rails-3.2simple-formmodel-associations

Creating default values in a new form derived from an associated model instance


I would like to populate form fields using simple_form with data stored in an associated model when creating a new record.

class Game < ActiveRecord:Base
  has_many :events
  attr_accessible :name, :number_of_players
end

class Event < ActiveRecord:Base
  belongs_to :game
  attr_accessible :name, :number_of_players
end

Different games require different numbers of players on a team (baseball:9, basketball: 5, football:11).

In my form, when creating an event, I have an association drop down where the user selects the game. I would like to pre-populate an event field for the number of players, which the user can override if needed. For example, basketball would populate the field with 5, but the user might want to change it to 3 since that specific event may be a 3 on 3 game. I do not want the game data modified.

Essentially, I am trying to create default values for a form based on values of an associated model instance selected within the same form. I've tried many approaches with no success.


Solution

  • How about:

    <%= f.input :number_of_players, :input_html => { :value => (number_of_players_value(f.object)} %>
    

    Define a number_of_players_value helper method:

    def number_of_players_value(event)
      event.new_record? ? event.game.number_of_players : event.number_of_players
    end
    

    This solution Provides that an event has a associated game as default. If the content of the number_of_players field should be changed when the users select a an other game than you need some JavaScript to achieve this.