Rails - I can't display locations on my users form using nested forms

六眼飞鱼酱① 提交于 2020-01-07 07:43:06

问题


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.

I have no errors on the console. But the fields (select or dropdowns, text_fields, etc) are not showing up. The database has records.

This is my user.rb model:

class User < ActiveRecord::Base

has_many :locations
   accepts_nested_attributes_for :locations   
end

This is my location.rb model:

class Location < ActiveRecord::Base
   belongs_to :user
end

This is my user form:

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

回答1:


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


来源:https://stackoverflow.com/questions/38063470/rails-i-cant-display-locations-on-my-users-form-using-nested-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!