views:

25

answers:

2

Hi,

Is that possible to establish a relationship between Tree and Branch such as:

class Tree < ActiveRecord::Base
  has_many :branches
end

class Branch < ActiveRecord::Base
  belongs_to :tree
end

But with an array of foreign keys branch_ids stored in Tree? I know it's the opposite of the default process, but I want to do so (just for testing).

Many thanks for any help.

A: 

you have to specify a new model (f.e. branchtree) - hbtm or another has_many :through

Then you could have multiple trees for one branch...

Lichtamberg
Thanks for your answer. But I don't want that (so it's multiple branches for one tree). I just would like to move the typical foreign key from Branch to Tree. Instead of having a foreign key *tree_id* in Branch, I would like a Tree may contain an array of *branch_ids* foreign key.
moshimoshi
But why? Thats a bad database schema, because its failing some canonical forms..?
Lichtamberg
A: 

As Lichtamberg mentioned it is a bad schema. Since you said "just for testing", if branch ids will be a column with comma separated values. You won't be able to establish a relatioship. But you can create an atribute like this

class Tree < ActiveRecord::Base
  def branches
      Branch.all(branch_ids.split(','))
  end
  def branches=(branches)
      branch_ids = branches.collect(&:id).join(',')
  end
end

But don't do this!!!

Deepak N
Wowwwww, many thanks! That really looks very nice. But okay, I don't do this... :)
moshimoshi