【问题标题】:Rails - I can't display locations on my users form using nested formsRails - 我无法使用嵌套表单在我的用户表单上显示位置
【发布时间】:2016-06-27 21:22:16
【问题描述】:

我无法使用嵌套表单显示属于用户的位置。

我想创建用户并将地址、城市、州等保存在位置模型中,并将姓名、用户名、电子邮件保存在用户模型中。

我在控制台上没有错误。但是字段(选择或下拉菜单、text_fields 等)没有显示出来。数据库有记录。

这是我的 user.rb 模型:

class User < ActiveRecord::Base

has_many :locations
   accepts_nested_attributes_for :locations   
end

这是我的 location.rb 模型:

class Location < ActiveRecord::Base
   belongs_to :user
end

这是我的用户表单:

<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
  <%= form_for(["admin", @user]) do |f| %>
    <% if @user.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

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

    <div class="field">
      <%= f.label :name %><br>
      <%= f.text_field :name %>
    </div>
    <div class="field">
      <%= f.label :username %><br>
      <%= f.text_field :username %>
    </div>
    <div class="field">
      <%= f.label :email %><br>
      <%= f.text_field :email %>
    </div>
    <div class="field">
      <%= f.label :password %><br>
      <%= f.text_field :password %>
    </div>

    <!-- Here is the nested form -->

    <%= f.fields_for :locations do |location| %>
      <%= location.label :country %>
      <%= location.select :country%>

      <%= location.label :state %>
      <%= location.text_field :state%>

    <% end %>

    <div class="actions form-group">
      <%= f.submit class: 'form-control' %>
    </div>
  <% end %>

【问题讨论】:

  • 您的@user 对象是否已有位置?如果没有,您需要构建一个到服务器作为第一个位置的占位符(创建时)。

标签: ruby-on-rails nested-forms nested-attributes


【解决方案1】:

将以下行添加到您的视图中:

<% f.object.locations.build if f.object.locations.empty? %>
<%= f.fields_for :locations do |location| %>
....

您也可以在控制器中添加此逻辑,但我会将其添加到视图中。为什么?因为如果你想在另一个控制器中重用这个表单,你将不得不复制你的代码。

如果您以后想添加多个位置,我建议您观看这两个 railscats:

http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2

【讨论】:

    猜你喜欢
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2012-07-08
    相关资源
    最近更新 更多