Rails-我无法使用嵌套表单在用户表单上显示位置 [英] Rails - I can't display locations on my users form using nested forms
问题描述
我无法使用嵌套表单显示登录到用户的位置.
I can't display the locations that belogns to the user using nested forms.
我要创建用户并在位置模型中保存地址,城市,州等,并在用户模型中保存名称,用户名和电子邮件.
I want to create the user and save the address, city, state, etc in location model and the name, username, email in the user model.
我在控制台上没有错误.但是没有显示字段(选择或下拉列表,text_fields等).数据库中有记录.
I have no errors on the console. But the fields (select or dropdowns, text_fields, etc) are not showing up. The database has records.
这是我的user.rb模型:
This is my user.rb model:
class User < ActiveRecord::Base
has_many :locations
accepts_nested_attributes_for :locations
end
这是我的location.rb模型:
This is my location.rb model:
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 %>
推荐答案
在您的视图中添加以下行:
Add the following line to your view:
<% f.object.locations.build if f.object.locations.empty? %>
<%= f.fields_for :locations do |location| %>
....
您也可以在控制器中添加此逻辑,但是我将其添加到视图中.为什么?因为如果您想在另一个控制器中重用此表单,则必须复制代码.
You can also add this logic in controller, but I would add it to the view. Why? Because if you would want to reuse this form in another controller, you will have to duplicate your code.
如果将来您想添加多个位置,我建议您观看以下两个臭鼬":
And if you want to add more than one location in the future, I would suggest you to watch these two railscats:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
这篇关于Rails-我无法使用嵌套表单在用户表单上显示位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!