Search code examples
ruby-on-railsrails-activerecordone-to-manyruby-on-rails-7

Rails new ActiveRecord build based on triangulation of two required 1:n resources?


(Sorry if this has been addressed before, can't find it.)

Let's say I've got three tables. I'll keep it simple (P = Post, C = Comment and U = User, but not what I'm actually developing): P ||-> C <-|| U, where P can have many Cs, and U can have many Cs. I've got my resource routes setup as Ps/[:p_id]/Us/[:u_id]/cs/[:c_id]. I need to create a /new C. From my understanding, typically if I was only building C from only P or U, I would just generate it from an P.c.build/U.c.build. But since I need both, and neither A nor C are directly hierarchical to each other, I'm trying to understand how to do this. I need three things:

  1. Appropriate *_path helper generated somehow with a new_p_u_c(@P, @U)
  2. Necessary .build alternative for triangulating both P and U with C.
  3. Necessary form_with:
    1. model: with @P and @U
    2. url: *_path create helper (p_u_cs(@P, @U)).
    3. Question: Do I use hidden input fields to store P and U, is will that be automatically generated within the forms_with's <form>?

Solution

  • If anyone finds this, hope it helps.

    1. It was indeed as simple as I had posed it: new_p_u_c_path(p_id: @P.id, u_id: @U.id). I wasn't aware that the paths helper was capable of dynamically accepting multiple arguments. Precautions:
      1. Pass them in the exact order as the route resources or (preferably) pass in the named arguments as shown above.
      2. If you don't use named arguments above and you're using a nice URL gem (I'm using friendly_id), you'll need to pass in the @P.id specifically instead of @P, or else the path helper won't be able to find it.
    2. I only used @P.c.build for this. It worked, but I'm not sure if it is even necessary at this point, since the only thing I needed was the @P.id, so see below...
    3. I passed in my form_with(model: @C, ...)
      1. Because the /new route already contained the @P.id and @U.id, the hidden_field automatically accepted p_id and u_id since I had my models setup with appropriate chaining logic.
      2. p_u_cs_path worked without passing any additional model arguments (again, see 3.1. above).
      3. I don't think this is necessary, now I think about it. The URL passed in 3.2. above should already include the IDs that rails will automatically parse.