Search code examples
ruby-on-railsrubyruby-on-rails-5simple-formsimple-form-for

How to fill edit form's nested inputs ? ( simple_fields_for ) Rails 5


i have a nested form. New method works well. But in my edit form nested inputs are empty. Here is my form :

  <%= simple_form_for @company , url: admin_company_path(@company) do |f| %>
        <%= f.simple_fields_for :licence do |p| %>
         <%= p.input_field  :number  %>  
        <% end %>
  <% end %>

my company model :

  accepts_nested_attributes_for :licence
  has_one :licence , inverse_of: :company , :dependent => :destroy

my licence model :

  belongs_to :company

my edit method in controller :

  def edit
    // i get company id with before_action
    @company.build_licence
  end

my new method in controller :

  def new
    @company = Company.new
    @company.build_licence
  end

new/create methods work great with this code. But edit form does not fill nested model inputs.


Solution

  • You say it doesn't fill the model inputs... but you are using build_license which creates a new, empty one every time... even if one exists already... it will blow the existing one away.

    You might need to do something like:

    def edit
      // i get company id with before_action
      @company.licence || @company.build_licence
    end