Simple_form:simple_fields_for不显示表单

时间:2016-03-15 03:18:13

标签: ruby-on-rails forms ruby-on-rails-4 simple-form-for

我试图只用一种形式创建两个模型。我的unitclass User < ActiveRecord::Base has_many :units, :through => :user_unit_assocs has_many :user_unit_assocs end 模型都与has_many相关联:通过关联。

user.rb

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

unit.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

users_controller.rb

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 %>

:name

当我运行代码时,表单只显示:emailunits:[:unitname]的输入字段,并且boost::gregorian::date current_date(boost::gregorian::day_clock::local_day()); boost::gregorian::date_duration dd(offset); boost::gregorian::date offset_date = current_date - dd; auto facet = new pt::time_facet("%Y-%m-%d"); std::stringstream ss; ss.imbue(std::locale(std::cout.getloc(), facet)); ss << offset_date; std::cerr << ss.str() << std::endl; 没有输入字段。如何在表单中显示输入字段?提前谢谢。

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

2 个答案:

答案 0 :(得分:1)

您需要在新操作中构建关联,而不是创建操作。

答案 1 :(得分:1)

添加

def new
  @user = User.new
  @user.units.build
end
控制器上的