Recently I started to experiment with turbo-frames, specifically lazy loading frames. In this process and the way I approached it, I noticed something that made we wonder whether there is a “Rails-y way” of organizing partials and views that I’ve missed.
Here’s the setup:
- Model
Foohas_manymodelBars. - Both Model
FooandBarhave corresponding controllers (e.g.,foos_controllerandbars_controller) with all the normal actions and views. - Foo’s controller’s
showaction/view wants to show all of theBarsit has.
All good so far. Now the experiment: Alter the foos_controller show view to include a turbo-frame with a src to display the Bars.
Here’s how I approached this:
- Create a sub-resource route on
foosfor thebars:
resources :foos do
resource :bars do
end
- Create a
turbo-framethis looks like this:
<turbo-frame id="bars" src="/foos/1/bars" loading="lazy"></turbo-frame>
Here’s where it got interesting (for me…a relative Rails novice)…
The route /foos/1/bars routes to the bars_controller’s index action (passing with it foo_id = 1 as a parameter)!
Hmmmm. Okay.
To this point I had a _bars.html.erb partial in the views/foos folder.
This is where I started wondering…
If I use this approach, I need to create (or move) the views/foos/_bars.html.erb over to views/bars/index.html (or similar) and simply have the bars_controller’s index (or similar) action render (with only the Bars for the foo_id).
Granted, I don’t need to structure routes (and controllers) this way. But it just got me wondering…
So with all of that (long-winded) back story, my question is this:
Is it considered the “Rails way” (if there is such a thing) that all views and partials (even when rendered from another model’s controller) should “live with” (i.e., be co-located with) the controller for that model?
In other words, using this example…
Should all Bar-related views and partials live in views/bars and be referenced from any other view that needs them?
(And vice-versa for Foo-related views and partials.)
Is this the preferred way? Is this a “cleaner” way (also possibly DRY-er)? Is this what a much more experienced Rails developer would expect if they joined my project?
P.S. This isn’t about designing and structuring things around turbo-frames. That just happened to be what raised this question in my mind.
Thanks in advance for anyone who has advice or opinions on this!