【问题标题】:Rails 3 ActiveAdmin. How to setup has_many and belongs_to with a different foreign key?Rails 3 ActiveAdmin。如何使用不同的外键设置 has_many 和 belongs_to?
【发布时间】:2012-01-09 20:27:50
【问题描述】:

所以我的货件最多可以有三个托运公司。所以我有这个...

shipment belongs_to shipper
shipper has_many shipments

但我在货件表中又添加了两列:shipper_id_2 和shipper_id_3。如何设置关联并让 ActiveAdmin 实现它?

【问题讨论】:

  • GoodEnough 下面提出的可能是正确的前进方向。如果您想在表中保留其他shipper_id,您可以通过使用 :foreign_key 属性并将其设置为列名来设置用于匹配的外键(例如 :foriegn_key => 'shipper_id_2 附加到您的关联) .

标签: ruby-on-rails ruby associations activeadmin


【解决方案1】:

我建议使用介于这两者之间的类将货物分配给托运人。

class ShippingAssignments
  belongs_to :shipment
  belongs_to :shipper
end

class Shipment
  has_many :shipping_assignments
  has_many :shippers, :through => :shipping_assignments
end

class Shipper
  has_many :shipping_assignments
  has_many :shipments, :through => :shipping_assignments
end

您可以通过验证器强制执行 3 个托运人的限制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    相关资源
    最近更新 更多