【问题标题】:has_many multiple associations with different nameshas_many 具有不同名称的多个关联
【发布时间】:2014-05-19 03:08:20
【问题描述】:

Ruby 2.1.0/Rails 4.0.2

我有一个总线模型和一个集群模型。它们如下所示:

class Bus < ActiveRecord::Base
  has_many :left_centroids, class_name: "Centroid"
  has_many :right_centroids, class_name: "Centroid"
end

class Centroid < ActiveRecord::Base
  belongs_to :bus
end

Bus 也有一个方法,基本上是 KMeans 算法,所以我运行它来替换旧的 left_centroids,然后替换 right_centroids。 Right 和 Left 在 Centroid Model 中给定字段的值不同。

我尝试通过简单的设置来保存它们:@bus.left_centroids = centroids_for_algorithmsupdate_attributes。但是每当我保存一个时,比如 left,right 就会被 left 的值覆盖,反之亦然,这在我的应用程序上下文中毫无意义。

我错过了什么吗?

更新:运行 K 均值算法(来自 ai4r gem,cmets 中的链接)后,我收集质心

def algorithm(direction)
  clusters = k_means_algorithm_part

  centroids_to_add_to_bus = Centroid.limit 0
  clusters.centroids.each do |centroid|
    cent = Centroid.create(
      :latitude => centroid[0].to_d,
      :longitude => centroid[1].to_d,
      :catch_time => centroid[2],
      :direction => direction,
      :bus_id => bus_id
    )
    centroids_to_add_to_bus.append cent
  end
  bus = Bus.find(bus_id)
  if direction
    bus.right_centroids = centroids_to_add_to_bus
  else
    bus.left_centroids = centroids_to_add_to_bus
  end
end

【问题讨论】:

标签: ruby-on-rails-4 associations rails-activerecord has-many


【解决方案1】:

您能否在质心表中添加另一列称为类型。现在您可以使用它对您的关联应用条件。像这样

 class Bus < ActiveRecord::Base
   has_many :left_centroids, class_name: "Centroid", -> { where type: 'left_centroid' }
   has_many :right_centroids, class_name: "Centroid", -> { where type: 'right_centroid' }
 end

不确定语法,但我认为这应该会有所帮助。

【讨论】:

  • 我可以,但质心已经有一个名为“方向”的列。我会尝试的。
  • 是的。只需使用关联中的条件。如果有帮助,请告诉我们。
  • 奇怪的是,它没有用。我设法避免用相同的模型声明两个字段。感谢您的帮助。
猜你喜欢
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多