我正在尝试以一种形式创建两个模型。我有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