1

can I transcribe the examples given at the Action View Form Helpers Guide (https://guides.rubyonrails.org/form_helpers.html#nested-forms) on Nested Forms to Nested Forms and the example given in the Routes Guide (https://guides.rubyonrails.org/routing.html#nested-resources) on nested resources to the case of Self-Joins as described in the Associations Guide (https://guides.rubyonrails.org/association_basics.html#self-joins)

Self-Joins

class Employee < ApplicationRecord
  has_many :subordinates, class_name: "Employee",
                          foreign_key: "manager_id"

  belongs_to :manager, class_name: "Employee", optional: true
end

Nested Form Helpers Example

<%= form_with model: @person do |f| %>
  Addresses:
  <ul>
    <%= f.fields_for :addresses do |addresses_form| %>
      <li>
        <%= addresses_form.label :kind %>
        <%= addresses_form.text_field :kind %>

        <%= addresses_form.label :street %>
        <%= addresses_form.text_field :street %>
        ...
      </li>
    <% end %>
  </ul>
<% end %>

Nested Route Helpers Example

resources :magazines do
  resources :ads
end
von spotz
  • 875
  • 7
  • 17

1 Answers1

-1

There is no difference at all between a self join and any other kind of assocation when it comes to routing or forms.

Your routes don't actually care at all about your models*. They just declare a set of routing rules that match incoming requests to controllers. So they care even less about your assocations. You can declare your RESTful routes however you want and its you as a programmer that actually dictates how this corresponds to your models. The fact that the table is self joining is an implementation detail and actually has nothing to do with how you should structure the application.

Your forms also don't care at all. When you use f.fields_for :subordinates it just calls the subordinates method on your model and iterates through it. It does not know about or care about the underlying tables. The same applies to accepts_nested_attributes. Thats kind of the point of the abstraction that assocations provide.

max
  • 96,212
  • 14
  • 104
  • 165
  • * Yes you can do crazy stuff where you use your models to generate routes but thats pretty far from normal. – max Jan 29 '20 at 11:28