ruby-on-railsformsruby-on-rails-4simple-form-for

Simple_form: simple_fields_for not showing the form


I'm trying to create two model in just one form. I have user and unit model both are associated with has_many :through association.

user.rb

class User < ActiveRecord::Base
  has_many :units, :through => :user_unit_assocs
  has_many :user_unit_assocs
end

unit.rb

class Unit < ActiveRecord::Base
  has_many :users, :through => :user_unit_assocs
  has_many :user_unit_assocs
end

users_controller.rb

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    @user.units.build
    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
  def user_params
      params.require(:user).permit(:username, :email, units_attributes:[:unitname])
    end
end

This is my form, users new

<%= simple_form_for(@user) do |f| %>
  <%= f.simple_fields_for :units do |unit| %>
    <%= unit.input :unitname, required: true %>
  <% end %>
  <%= f.input :name, required: true %>
  <%= f.input :email, required: true %>

  <%= f.button :submit %>
<% end %>

When I run the code, the form only showing a input-field for :name and :email and there is no input-field for units:[:unitname]. How can I show the input-field in the form? Thanks in advance.

References:

  1. Rails 4: accepts_nested_attributes_for and mass assignment
  2. https://github.com/plataformatec/simple_form/wiki/Nested-Models

Solution

  • Add

    def new
      @user = User.new
      @user.units.build
    end
    

    on your controller