1

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.

2
  • Use the term "relationship". A [relation](en.wikipedia.org/wiki/Relation_(database%29) is not what you think it is. Commented Oct 24, 2010 at 9:02
  • Thank you for the terminology, I will use this term. :) Commented Oct 24, 2010 at 10:08

2 Answers 2

1

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!!!

Sign up to request clarification or add additional context in comments.

1 Comment

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

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...

2 Comments

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.
But why? Thats a bad database schema, because its failing some canonical forms..?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.