Noob stuck - complex model relationships and one of two foreign keys not getting saved or updated

Rather than posting my code and asking “what’s wrong”, here’s a
simpler version: The problem is my C’s are not saving or updating the
foreign key for B when I create or update a C. The foreign key value
remains nil.

A has many Bs
A has many Cs

B has many Cs
B belongs to A
The B model contains an A_id foreign key field

C belongs to A
C belongs to B
The C model contains both A_id and B_id foreign key fields

So a C can either belong directly to A (with B being null) or it can
belong to both an A and B. This is not a C belongs to A through B
relationship - Cs can belong directly to an A. Cs are created using
current_A.Bs.new, so they are already automatically scoped to the
correct A.

When creating or editing a C, a table of possible Bs is created and
displays correctly and I am able to select one of the possible choices
or leave it set to the default (‘none selected’ / nil value) choice.
This all worked fine before I layered on the A model. I was able to
create Cs that were either free standing or belonged to a B.

Now, the terminal console shows the URL string contains: “B_id”=>“15”,
so it appears that the select function is grabbing the correct id from
the table for the B choice that was selected. However, when I then
debug the updated C record, the B_id value is always nil.

So, why isn’t the B_id field getting updated in this situation?

Thanks in advance.

On Mar 16, 5:47 pm, ander31415 [email protected] wrote:

Now, the terminal console shows the URL string contains: “B_id”=>“15”,
so it appears that the select function is grabbing the correct id from
the table for the B choice that was selected. However, when I then
debug the updated C record, the B_id value is always nil.

So, why isn’t the B_id field getting updated in this situation?

Hard to say without seeing what you’re actually doing. I know you’ve
deliberately not posted code, but without code, unless your basic
premise is fundamentally flawed it’s just guesswork.

Fred

My error (Noob!) - the model for C had set attr_protected for the B_id
field. So Rails was doing exactly as I instructed it. I found this
by reviewing the development log, which included a warning that B_id
was protected against mass updates.

Thanks all.

On Mar 16, 3:13 pm, Frederick C. [email protected]
wrote:

On Mar 16, 5:47 pm, ander31415 [email protected] wrote:
*** CUT ***