Search code examples
ruby-on-railsformsassociationsbelongs-tohas-one

How to create a view containing field of an associated model in rails?


In my project, I have an Organization model and an Address model. Here is the association beetween the models:

class Organization < ApplicationRecord
    belongs_to :adresse
end

class Organization < ApplicationRecord
    has_one :organization
end

I would like to know how to create a new form and include attributes from both model. For the moment, my organization/new.html.erb look like this:

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

And I tried to add this to the form but address method is not recognized:

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

In controller, I have access to the address of the organization like:

@organization.address.streetNumber

PS: I'm new to Rails ;)


Solution

  • That's what fields_for is 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 %>