Question

Seems simple, but having an issue:

model A
belong_to :B

model B
has_many :A

database tables:
table A:
id,...,b_id

table B:
id,...

When trying to create a new A, I set (an existing) B by doing: a.b = B

I get an error saying "b can't be blank"

Was it helpful?

Solution

Instead of doing a.b = B, do a.b_id = B.id.

OTHER TIPS

Think about how your collection and parent-child relationships work. You can -as suggested- add the ID of the relevant B to your A, but you may alternatively want to say B.a[] = a which would add "a" to your the "a" collection of your object "B". That way the relationship is set up in a more intuitive way, oriented towards the parent object rather than the child.

You should also be able to do newA = B.as.build ('as' being the plural of a).

Of course your examples of 'A, a, B and b` are very confusing! In the future use 'customer' & 'order' or 'blog' & 'post' or anything but cryptic letters with no meaning.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top