Simple_form:simple_fields_用于不显示表单

问题描述 投票:0回答:2

我正在尝试以一种形式创建两个模型。我有

user
unit
模型都与 has_many 相关联:通过关联。

用户.rb

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

单位.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

这是我的表格,用户们

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
:email
的输入字段,并且没有
units:[:unitname]
的输入字段。如何在表单中显示输入字段?预先感谢。

参考资料:

  1. Rails 4:accepts_nested_attributes_for 和批量分配
  2. https://github.com/plataformatec/simple_form/wiki/Nested-Models
ruby-on-rails forms ruby-on-rails-4 simple-form-for
2个回答
3
投票

添加

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

在您的控制器上


1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.