레일스에서 자체 참조 클래스에 대해 많이 읽었지만 여전히 작동시키는 데 문제가 있습니다.레일스에서 자체 참조 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 만 저장합니다.
내가 뭘 잘못하고 있니?
<< b' 당신은 a.save''호출 ? –
이 작업이 끝났습니다. 나는 이름을 바꿨다 - 그것이 중요한 것인지 나는 모른다. 나는 소스가 무언가를 사용하는 어리석은 이름이었던 곳을 읽었다. 이것은 작동합니다 : create_table "article_relationships", : force => true do | t | t.integer "PARENT_ID" t.integer는 ... 끝 CREATE_TABLE "기사", "child_id": | t 힘 => 사실 할 일을 | t.string "name" ... end – Edward