rails中实现自关联

例:要求存储多个城市各自的坐标和两两之间的距离。
 
可以这样实现:
class CreateCities < ActiveRecord::Migration
  def self.up
    create_table :cities do |t|
      t.string :city_name
      t.decimal :x_axis, :precision=>8, :scale=>2
      t.decimal :y_axis, :precision=>8, :scale=>2
      t.timestamps
    end
  end
  def self.down
    drop_table :cities
  end
end
 
class CreateDistances < ActiveRecord::Migration
  def self.up
    create_table :distances do |t|
      t.integer :start_id
      t.integer :end_id
      t.decimal :distance, :precision=>8, :scale=>2
      t.timestamps
    end
  end
  def self.down
    drop_table :distances
  end
end
 
 
-------
class City < ActiveRecord::Base
  has_many :distances_as_start, :foreign_key=>"start_id", :class_name=>'Distance'
  has_many :distances_as_end, :foreign_key => "end_id", :class_name=>"Distance"
  has_many :starts, :through=>:distances_as_end
  has_many :ends, :through=>:distances_as_start
end
 
 
class Distance < ActiveRecord::Base
  belongs_to :start,:class_name=>"City", :foreign_key=>"start_id"
  belongs_to :end,:class_name=>"City", :foreign_key=>"end_id"
end
 
 
 

你可能感兴趣的:(职场,Rails,休闲,自关联)