has_many具有不同名称的多个关联

时间:2014-05-19 03:08:21

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

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

总线还有一个基本上是KMeans算法的方法,所以我运行它来替换旧的left_centroids,然后替换right_centroids。右和左在Centroid模型中给定字段的值不同。

我尝试通过简单设置保存这些内容:@bus.left_centroids = centroids_for_algorithms以及update_attributes。但每当我保存一个,左说,右边用左边的值覆盖,反过来,这在我的应用环境中毫无意义。

我错过了什么吗?

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

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

1 个答案:

答案 0 :(得分:1)

可以在质心表中添加另一个名为type的列。现在,您可以使用它来为您的关联应用条件。喜欢这个

 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

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