ruby-on-rails Simple_form:simple_fields_表示不显示表单

biswetbf  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(120)

我试图在一个表单中创建两个模型。我有userunit模型,它们都与has_many:通过关联关联。
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


这是我的表单,用户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 and mass assignment
  2. https://github.com/plataformatec/simple_form/wiki/Nested-Models
5lwkijsr

5lwkijsr1#

添加

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

字符串
控制器上

5sxhfpxr

5sxhfpxr2#

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

相关问题