ActiveRecord relation using an array of foreign keys

扶醉桌前 提交于 2019-12-24 17:02:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!