2011-11-15 2 views
2

레일스에서 ​​자체 참조 클래스에 대해 많이 읽었지만 여전히 작동시키는 데 문제가 있습니다.레일스에서 ​​자체 참조 has_many through

나는 기사의 종류가 있고 원본 기사에서 결과 기사에 이르기까지 서로를 참조하고 그 반대를 찾을 수 있기를 바랍니다. 그래서 has_many를 통해 링크를 호출하는 다른 클래스를 사용하려고합니다.

내 스키마 모델은

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 

입니다

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 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를 사용하여 함께 기사를 링크 할 수 있지만, 링크 테이블은 source_id가 아닌 outcome_id 만 저장합니다.

내가 뭘 잘못하고 있니?

+0

<< b' 당신은 a.save''호출 ? –

+0

이 작업이 끝났습니다. 나는 이름을 바꿨다 - 그것이 중요한 것인지 나는 모른다. 나는 소스가 무언가를 사용하는 어리석은 이름이었던 곳을 읽었다. 이것은 작동합니다 : create_table "article_relationships", : force => true do | t | t.integer "PARENT_ID" t.integer는 ... 끝 CREATE_TABLE "기사", "child_id": | t 힘 => 사실 할 일을 | t.string "name" ... end – Edward

답변

2

나는 결국이 일을 얻었다. 나는 이름을 바꿨다 - 그것이 중요한 것인지 나는 모른다. 나는 소스가 무언가를 사용하는 어리석은 이름이었던 곳을 읽었다.

그래서이 작품 것입니다 :`a.outcomes를 호출 한 후

내 스키마

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

는 "kung pao"보다 맛 있습니다. –