想在 people 表内找出是朋友的 person。
<code>
# people 表
create_table :people do |t|
t.column :name, :string
end
# 连接模型 authorized 用于表示其是否是我的朋友。
# 关联的朋友表 friendships
create_table :friendships do |t|
t.column :person_id, :integer
t.column :friend_id, :integer
t.column :authorized, :boolean, :default => false
end
class Friendship < ActiveRecord::Base
belongs_to :person
# 其模型并不存在,所以要给出 :class_name 及 :foreign_key 选项。
# 以让活动记录知道上哪里去找记录。
belongs_to :friend, :class_name => “Person”, :foreign_key => “friend_id”
end
class Person < ActiveRecord::Base
# 设定一对多连接,告诉活动记录一个 person 可以有多个 friendships。
has_many :friendships
# 创建 has_many :through 关联,在 friendships 内找寻 friends。
has_many :friends, :through => :friendships
# 如果查寻只认识的朋友的例子。
has_many :authorized_friends, :through => :friendships, :source => :friend, :conditions => [ “authorized = ?”, true ]
# 如果得到不认识朋友的例子。
has_many :unauthorized_friends, :through => :friendships, :source => :friend, :conditions => [ “authorized = ?”, false ]
end
</code>
This example is for modeling digraphs.
create_table "nodes" do |t|
t.column "name", :string
t.column "capacity", :integer
end
create_table "edges" do |t|
t.column "source_id", :integer, :null => false
t.column "sink_id", :integer, :null => false
t.column "flow", :integer
end
class Edge < ActiveRecord::Base
belongs_to :source, :foreign_key => "source_id", :class_name => "Node"
belongs_to :sink, :foreign_key => "sink_id", :class_name => "Node"
end
class Node < ActiveRecord::Base
has_many :edges_as_source, :foreign_key => 'source_id', :class_name => 'Edge'
has_many :edges_as_sink, :foreign_key => 'sink_id', :class_name => 'Edge'
has_many :sources, :through => :edges_as_sink
has_many :sinks, :through => :edges_as_source
end
http://blog.hasmanythrough.com/articles/2006/04/21/self-referential-through |