Has_many and belons_to Problem

Dear all,

I have a problem with the relations of a model. The problem is the following.

I have 2 models. Page and PeContainer. Page: has_and_belongs_to_many :pe_containers

PeContainer belongs_to :page has_many :pages


---->PeContainer -------->Page ------------>PeContainer

So my mainproblem is to get the parentpage of the PeContainer. I can only access the childpages. Can anyone help? Thanks in advance!

Kind regards Alex

Hmm, that’s a very interesting relationship.

[1] Something to try first – and even if this is not part of the problem, It may help you in debugging – is to name the relationships more directly. In PeContainer, name them “parentpage” and “childpages”, etc.

[2] I think your problem might lie in the fact that in your Page model you have only declared one relationship, when really there are two. Consider the case of a Book, which has an author and an editor, both of which are People. You would declare the relationships seperately, you would not say “has many People”. Similarly, in this case you should HABTM :parent_containers and HABTM :child_containers.

Let us know if that gets you anywhere.

Looks to me like your page model is incorrect, judging from your text diagram. Assuming your model is a tree with alternating node types, you probably want:

Page: belongs_to :pe_container (parent) has_many :pe_containers (children)

PeContainer: belongs_to :page (parent) has_many :pages (children)

- donald

I just re-read your email and realized that I did not address the problem you stated :). But I think making your relationships more explicit is a good place to start.

Yes, Donald’s suggestion is better than mine :slight_smile:

(although I would still name them more specifically)

Dear all!

Thanks for fast answering.

I changed the Modelrelations to the settings Donald wrote. But this didn't help.

I can't rename my models, because I have an unlimited tree. So here is an example of what i do:

I have a page (id=1) This page has a container (id=1) This Container has 2 pages (id=2 & id=3) Page 1 has a container (id=2) Page 2 has a container (id=3)

So now I have to walk up the tree. So if I have the container (id=1) I need to get the parentpage (id=1), but I only can access the 2 childpages. So is this issue resolvable?

Thanks in advance!

Kind regards Alex