如何在rails中创建包含关联模型字段的视图?

时间:2017-10-13 21:04:17

标签: ruby-on-rails forms associations belongs-to has-one

在我的项目中,我有一个Organization模型和一个Address模型。以下是模型之间的关联:

class Organization < ApplicationRecord
    belongs_to :adresse
end

class Organization < ApplicationRecord
    has_one :organization
end

我想知道如何创建新表单并包含两个模型的属性。目前,我的组织/ new.html.erb看起来像这样:

<%= form_with(model: organization, local: true) do |form| %>
  <% if organization.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(organization.errors.count, "error") %> prohibited this organization from being saved:</h2>
     <ul>
       <% organization.errors.full_messages.each do |message| %>
         <li><%= message %></li>
       <% end %>
     </ul>
   </div>
  <% end %>

  <div class="field">
    <%= form.label :organizationName%>
    <%= form.text_field :organizationName, id: :organization_organizationName %>
  </div>

  <div class="field">
    <%= form.label :email %>
    <%= form.text_field :email, id: :organization_email %>
  </div>

  <div class="field">
    <%= form.label :website %>
    <%= form.text_field :website, id: :organization_website %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

我尝试将其添加到表单中,但无法识别地址方法:

<div class="field">
  <%= form.label :streetNumber %>
  <%= form.text_field :organization.address.streetNumber%>
</div>

在控制器中,我可以访问组织的地址,如:

@organization.address.streetNumber

PS:我是Rails的新手;)

1 个答案:

答案 0 :(得分:1)

这就是fields_for的用途。

<%= form_for @person do |person_form| %>
  First name: <%= person_form.text_field :first_name %>
  Last name : <%= person_form.text_field :last_name %>

  <%= fields_for :permission, @person.permission do |permission_fields| %>
    Admin?  : <%= permission_fields.check_box :admin %>
  <% end %>

  <%= person_form.submit %>
<% end %>