【发布时间】: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