moshimoshi
moshimoshi

Reputation: 251

ActiveRecord relation using an array of foreign keys

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.

Upvotes: 1

Views: 2822

Answers (2)

Deepak N
Deepak N

Reputation: 2571

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

Upvotes: 1

BvuRVKyUVlViVIc7
BvuRVKyUVlViVIc7

Reputation: 11811

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

Upvotes: 0

Related Questions