Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I properly Shallow nest while doing a Many to Many association?

Brendan Feltrup-Exum asked in Rails

So I am teaching myself rails through online tutorials and such. I have followed many on how to make a CRUD. I have learned about nested routes and how to accept attributes and dependents, etc. Now I want to work with a nested structure (multi tiered) keeping it shallow for the sake of best practices while connecting them all together. I have used this tutorial as how to do nested routes:
https://www.digitalocean.com/community/tutorials/how-to-create-nested-resources-for-a-ruby-on-rails-application

I have 3 Controllers: Project, Script Location and Location (I only edited the Script Location to do the nested routes)
4 Models: Project, Script Location, Location and Script Locations Location

class Project < ApplicationRecord
has_many :script_locations, dependent: :destroy
end

class ScriptLocation < ApplicationRecord
belongs_to :project
has_many :script_locations_locations
has_many :locations, through: :script_locations_locations
accepts_nested_attributes_for :locations
end

class Location < ApplicationRecord
has_many :script_locations_locations
has_many :script_locations, through: :script_locations_locations
accepts_nested_attributes_for :script_locations
end

class ScriptLocationsLocation < ApplicationRecord
belongs_to :location
belongs_to :script_location
end

I started by doing a traditional nested route for Project to Script Location since if I delete the Project I want the Script Location to be destroyed too. Now I know triple nesting is not advisable so I left Location on its own for now. I have my join table setup and its technically joining the models and connecting everything in the browser. I just would like to figure out how to from Script Locations add a new Location that is associated with that already. Can anyone suggest how to best do this?

In my current repo I have it where I can associate it after the fact from the Locations side. Key issue is that I want to keep the locations saved in the database even if I delete the project so I can associate them later to a Script Location.
https://github.com/senorlocksmith/nested_forms

Reply

I have tried doing something like this, but it kind messes things up. Between the shallow part and some of the controller/views parts I am lost.

resources :projects, shallow: true do
resources :script_locations do
resources :locations
end
end

Thanks in advance for any help.

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,563+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.