Rails Devise Simple_form在提交时嵌套了2个模型

时间:2014-03-28 16:37:02

标签: ruby-on-rails ruby forms devise

我有一个表单,您可以注册为普通用户,另一个表单可以创建一个公司'一旦你注册了。但是我想创造一个“第三个”。表单,您可以在其中创建公司和新用户,因此我需要在两个模型上创建。

_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 %>

company.rb

class Outfitter < ActiveRecord::Base
has_many :users

accepts_nested_attributes_for :users
end

user.rb

belongs_to :company

如果用户尚未登录,则应显示用户输入字段和提交按钮但不显示,只显示公司输入字段。我得到了未定义的方法`model_name&#39;对于NilClass:Class&#39;

1 个答案:

答案 0 :(得分:1)

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

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

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

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