例:要求存储多个城市各自的坐标和两两之间的距离。
可以这样实现:
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.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
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.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
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
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
belongs_to :start,:class_name=>"City", :foreign_key=>"start_id"
belongs_to :end,:class_name=>"City", :foreign_key=>"end_id"
end
本文转自 fsjoy1983 51CTO博客,原文链接:http://blog.51cto.com/fsjoy/162753,如需转载请自行联系原作者