问题
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.
回答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!!!
回答2:
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...
来源:https://stackoverflow.com/questions/4007609/activerecord-relation-using-an-array-of-foreign-keys