使用外键数组的ActiveRecord关系 [英] ActiveRecord relation using an array of foreign keys

查看:108
本文介绍了使用外键数组的ActiveRecord关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可能在分支之间建立关系,例如:

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

但是带有一系列存储在Tree中的外键 branch_ids ?我知道这与默认过程相反,但我想这样做(仅用于测试)。

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

非常感谢您的帮助。

推荐答案

正如利塔姆伯格提到的那样,这是一个错误的模式。因为您说的是仅用于测试,所以
如果分支ID将是一列用逗号分隔的值。您将无法建立亲戚关系。但是您可以创建这样的属性

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

这篇关于使用外键数组的ActiveRecord关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆