Search code examples
ruby-on-railsformsruby-on-rails-4simple-formsti

Rails / STI - How do I show a different form based on the type?


There are 3 different types inheriting from the same model. Each has one unique attribute that is irrelevant to the others.

If there is a link for each type, is there a way to use the same form, but dynamically show the relevant fields for each type?

Or do I have to create a different form for each and use a hidden field to tell the controller which type to create?


Solution

  • I am assuming that you are passing a variable in the query string based on what hidden field you want to show

    if this is the case this is what I would do

    = simple_form_for(@model, :html => {:class => 'form-horizontal' }) do |f|
      ...
      - if params[:what_hiddind_filld_to_show] == 'type1'
        = f.input :fild_name, as: :hidden, , input_html: { value: '1' }
      - elsif params[:what_hiddind_filld_to_show] == 'type2'
        = f.input :fild_name, as: :hidden, , input_html: { value: '2' }
      - elsif params[:what_hiddind_filld_to_show] == 'type3'
        = f.input :fild_name, as: :hidden, , input_html: { value: '3' }
      - else
        = f.input :fild_name, as: :hidden, , input_html: { value: 'default' }
    

    I hope this puts you in the right track