Search code examples
ruby-on-railsformsdefaultsimple-form

How to set default value for association with simple_form?


I'd like to do something like this:

<%= f.association :productgroup, default: params[:productgroup_id] %>

The params should only be used if there is no value (lets say for new records), so selected: is not what I'm looking for because it overrides the value when I edit the record.

Thanks, Andreas


Solution

  • Set the value in your controller for the form object eg

    controller

    def show
        @product = Product.new();
        @product.product_group = ProductGroup.find(1) // set default
    end
    

    view

    simple_form_for @product do |f|
        f.association :product_group