【问题标题】:Simple_form: simple_fields_for not showing the formSimple_form:simple_fields_for 不显示表单
【发布时间】:2016-03-15 03:18:13
【问题描述】:

我正在尝试以一种形式创建两个模型。我有 userunit 模型都与 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 and mass assignment 2.https://github.com/plataformatec/simple_form/wiki/Nested-Models

【问题讨论】:

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


    【解决方案1】:

    添加

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

    在你的控制器上

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢。我只是找不到我在代码中做错的地方。再次感谢。
      猜你喜欢
      • 2013-08-26
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2018-10-02
      • 1970-01-01
      • 2018-01-17
      相关资源
      最近更新 更多