On Jul 17, 6:15 am, Felipe <[email protected]> wrote:
> I have an aggregate with 3 children models
>
> class Aggregate
> one_to_one :first_children
> one_to_one :second_children
> one_to_one :third_children
>
> nested_attributes :first_children
> nested_attributes :second_children
> nested_attributes :third_children
> end
>
> class FirstChildren
> many_to_one :aggregate
> end
>
> class SecondChildren
> many_to_one :aggregate
> end
>
> class ThirdChildren
> many_to_one :aggregate
> end
>
> I'm using fields for and:
>
> - in the new action when I set @aggregate.first_children =
> FirstChildren.new I get the error *"does not have a primary key"*
> - in the new action when I create a @first_children = FirstChildren.new
> and use it in the partial view with fields for I don't get the previous
> error but I get a constraint error from Postgres telling me that the column
> aggregate_id from the FirstChildren, SecondChildren and ThirdChildren was
> not se
>
> The question is: how can I create this object with it's children?
>
> Before posting here I took a look in the group and google but unfortunately
> I could not come up with any solution.
You can't do:
@aggregate.first_children = FirstChildren.new
if @aggregate is a new record, because in order for that to work, it
needs to set aggregate_id in the FirstChildren.new, so @aggregate has
to have a primary key (which is generally won't have until after
saving).
Have you looked at the nested_attributes specs? The API is roughly:
@aggregate.first_children.attributes = {...}
@aggregate.save
This handles things correctly by delaying the saving of the
first_children until after the @aggregate is saved.
Also, I can't help but commenting on your database design. If you are
trying to interact with an existing database, obviously you have to
live with it. If you are designing a new database, I would recommend a
better approach, something like:
class Aggregate
one_to_many :children
nested_attributes :children
end
class Child
many_to_one :aggregate
end
If you have to stick the an existing design that use three separate
columns, you probably should at least rename your models and
associations:
class Aggregate
one_to_one :first_child
one_to_one :second_child
one_to_one :third_child
nested_attributes :first_child
nested_attributes :second_child
nested_attributes :third_child
end
class FirstChild
many_to_one :aggregate
end
class SecondChild
many_to_one :aggregate
end
class ThirdChild
many_to_one :aggregate
end
Generally, model names and *_to_one association names are singular,
and *_to_many association names are plural.
Jeremy
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/sequel-talk?hl=en.