2011-11-15 85 views
2

我已經讀了很多關於Rails中的自引用類,但仍然有問題讓他們工作。自引用has_many通過Rails

我有一類文章,我希望它們能夠相互引用,從源文章到結果文章 - 然後能夠找到相反的內容。所以我想通過使用另一個名爲Links的類來做一個has_many。

我的模式是

create_table "articles", :force => true do |t| 
    t.string "name" 
    t.text  "body" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "links", :force => true do |t| 
    t.integer "source_id" 
    t.integer "outcome_id" 
    t.string "question" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

這些模型

class Article < ActiveRecord::Base 
    has_many :links_as_source, :foreign_key => "source_id", :class_name => "Link" 
    has_many :sources, :through => :links_as_source 

    has_many :links_as_outcome, :foreign_key => "outcome_id", :class_name => "Link" 
    has_many :outcomes, :through => :links_as_outcome 
end 

class Link < ActiveRecord::Base 
    belongs_to :source, :foreign_key => "source_id", :class_name => "Article" 
    belongs_to :outcome, :foreign_key => "outcome_id", :class_name => "Article" 
end 

我可以創建在控制檯的文章,我可以用a.outcomes << b聯繫在一起的文章,但鏈接表僅存儲outcome_id,而不是source_id。

我在做什麼錯?

+0

調用'a.outcomes後<< B'你叫'a.save' ? –

+0

我最終得到了這個工作。我改了名字 - 我不知道這是否重要。我確實在某個地方看過這個消息來源是一個愚蠢的名字,用於某些事情。 所以這是什麼工作: create_table「article_relationships」,:force => true do | t | t.integer「parent_id」 t.integer「child_id」 ... end create_table「articles」,:force => true do | t | t.string「名稱」 ... 結束 – Edward

回答

2

我得到了這個工作到底。我改了名字 - 我不知道這是否重要。我確實在某個地方看過這個消息來源是一個愚蠢的名字,用於某些事情。

因此,這是什麼在起作用:

我的架構

create_table "article_relationships", :force => true do |t| 
    t.integer "parent_id" 
    t.integer "child_id" 
    ... 
end 

create_table "articles", :force => true do |t| 
    t.string "name" 
    ... 
end 

我的文章模型

has_many :parent_child_relationships, 
      :class_name  => "ArticleRelationship", 
      :foreign_key => :child_id, 
      :dependent  => :destroy 
has_many :parents, 
      :through  => :parent_child_relationships, 
      :source   => :parent 

has_many :child_parent_relationships, 
      :class_name  => "ArticleRelationship", 
      :foreign_key => :parent_id, 
      :dependent  => :destroy 
has_many :children, 
      :through  => :child_parent_relationships, 
      :source   => :child 
+0

這節省了我的時間和小時數,應該設置爲答案。非常感謝! 我可以找到解決方案的自我參考有許多通過,從父母,但被難倒,以協商從小孩工作。這解決了它出色! –

+1

比'宮袍'更美味 –