用户形象图片

has_many :through 实现自引用连接


想在 people 表内找出是朋友的 person

# people

create_table :people do |t|

t.column :name, :string

end

<O></O>

# 连接模型 authorized 用于表示其是否是我的朋友。

# 关联的朋友表 friendships

create_table :friendships do |t|

t.column :person_id, :integer

t.column :friend_id, :integer

t.column :authorized, :boolean, :default => false

end

<O></O>

class Friendship < ActiveRecord::Base

belongs_to :person

<O></O>

# 其模型并不存在,所以要给出 :class_name :foreign_key 选项。

# 以让活动记录知道上哪里去找记录。

belongs_to :friend, :class_name => “Person”, :foreign_key => “friend_id”

end

<O></O>

class Person < ActiveRecord::Base

# 设定一对多连接,告诉活动记录一个 person 可以有多个 friendships

has_many :friendships

# 创建 has_many :through 关联,在 friendships 内找寻 friends

has_many :friends, :through => :friendships

<O></O>

# 如果查寻只认识的朋友的例子。

has_many :authorized_friends, :through => :friendships, :source => :friend, :conditions => [ “authorized = ?”, true ]

<O></O>

# 如果得到不认识朋友的例子。

has_many :unauthorized_friends, :through => :friendships, :source => :friend, :conditions => [ “authorized = ?”, false ]

end

 

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

<O></O>

<O></O>

http://blog.hasmanythrough.com/articles/<ST1 isrocdate="False" islunardate="False" day="21" month="4" year="2006">2006/04/21</ST1>/self-referential-through

回到帖子顶部