Rails --fields_for不起作用? [英] Rails -- fields_for not working?

查看:70
本文介绍了Rails --fields_for不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我运行Rails服务器并转到站点上的学校/新页面时,会出现带有标签"school"(我可以在其中输入学校名称)的字段,但在fields_下的所有其他字段均用于输入学校管理员的信息不会显示在我的网站上-当我在表单上使用检查元素"时,好像他们根本不在.他们为什么不出现在我的页面上?

When I run the rails server and go to the school/new page on my site, the field with the label "school" where I can enter the school's name appears, but all the other fields under fields_for which are for entering the school administrator's info do not show up on my site -- when I use "inspect element" on my form it is like they are not even there. Why aren't they appearing on my page?

<%= form_for(@school) do |f| %>
  <% if @school.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@school.errors.count, "error") %> prohibited this school from being saved:</h2>

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

  <div class="field">
    <%= f.label :school %><br />
    <%= f.text_field :name %>
  </div>
  <%= f.fields_for :admin do |f2| %>
    <div class="field">
      <%= f2.label "administrator name" %><br />
      <%= f2.text_field :name %>
    </div>
    <div class="field">
      <%= f2.label "administrator email" %><br />
      <%= f2.text_field :email %>
    </div>
    <div class="field">
      <%= f2.label "administrator gender" %><br />
      <%= f2.text_field :gender %>
    </div>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

推荐答案

 <%= f.fields_for :admin do |f2| %>

尝试删除f.

尝试一下:

<%= fields_for :admin do |f2| %>

有两种使用field_for的方式:

There is two way to use field_for:

一个通用的. (例如我的示例).

A generic one. (like my example).

一个嵌套的.

要使用嵌套的field_for(f.field_for),必须正确设置模型对象

To use the nested field_for (f.field_for), your model object must be setup correctly

例如:与@school和@admin的关系

Ex: Relation with @school and @admin

class School< ActiveRecord::Base
  has_one :admin
  accepts_nested_attributes_for :admin
end

最后,取决于在模型对象上设置关系的方式,有多种使用field_for的方法.

In the end, there is multiple ways of using field_for depending on how you setup the relations on your model object.

指南详细说明所有可能的设置.您可能会发现为什么它对您不起作用.

This guide explain in details all the possible setup. You might find why it was not working for you.

我敢打赌,您的Admin和School模型对象之间没有关系,或者您没有在您的School对象中放置accepts_nested_attributes_for:admin.

My bet is your Admin and School model object are not in a relation, or you didn't put the accepts_nested_attributes_for :admin in your School object.

这篇关于Rails --fields_for不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆