【问题标题】:Rails Devise Simple_form nested 2 models on submitRails 在提交时设计 Simple_form 嵌套 2 个模型
【发布时间】:2014-03-28 16:37:02
【问题描述】:

我有一个表单,您可以在其中注册为普通用户,另一个表单可以在您注册后创建一个“公司”。但我想创建一个“第三种”表单,您可以在其中同时创建一个公司和一个新用户,所以我需要在这两个模型上创建。

_form.html.erb

<%= simple_form_for(@company) do |f| %>
 <% if @company.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@company.errors.count, "error") %> prohibited this company from being saved:</h2>

  <ul>
  <% @company.errors.full_messages.each do |msg| %>
    <li><%= msg %></li>
  <% end %>
  </ul>
 </div>
<% end %>

<div class="field">
 <%= f.label :name %><br>
 <%= f.text_field :name, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :address %><br>
 <%= f.text_area :address, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :business_phone %><br>
 <%= f.text_field :business_phone, :class => "input-txt form-control" %>
</div>
<div class="field">
 <%= f.label :cell_phone %><br>
 <%= f.text_field :cell_phone, :class => "input-txt form-control" %>
</div>

<% if user_signed_in? %>

<div class="actions">
 <%= f.submit %>
</div>

<% else %>

 <% simple_fields_for(@users) do |f| %>

      <p><%= f.label :email%><br/>
        <%= f.email_field :email, :class => "input-txt form-control" %>
      </p>

      <p><%= f.label :password %><br />
        <%= f.password_field :password, :class => "input-txt form-control" %>
      </p>

      <p><%= f.label :password_confirmation %><br />
        <%= f.password_field :password_confirmation, :class => "input-txt form-control" %>
      </p>

<div class="actions">
  <%= f.submit %>
</div>
<% end %>

<% end %>

<% end %>

公司.rb

class Outfitter < ActiveRecord::Base
has_many :users

accepts_nested_attributes_for :users
end

用户.rb

belongs_to :company

如果用户尚未登录但它没有登录,它应该显示用户输入字段和提交按钮,它只显示公司输入字段。我得到 NilClass:Class 的“未定义方法 `model_name'”

【问题讨论】:

    标签: ruby-on-rails ruby forms devise


    【解决方案1】:

    如果没有与装备商关联的用户记录,simple_fields_for 将不会显示用户。在您的控制器中执行以下操作:

    def new
      @outfitter = Outfitter.new
      @outfitter.users.build
    end
    

    这将在@outfitter 用户关系中创建一个空白用户记录。

    然后在您的视图中将simple_fields_for(@user) 更改为simple_fields_for :users

    【讨论】:

    • 另外,将fields_for :users do |f| 更改为fields_for :users do |u|,您可以在:users 块中使用u.input
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多