Edw*_*ard 3 ruby-on-rails ruby-on-rails-3
我已经阅读了很多关于 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
Run Code Online (Sandbox Code Playgroud)
模型是
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
Run Code Online (Sandbox Code Playgroud)
和
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
Run Code Online (Sandbox Code Playgroud)
我可以在控制台中创建文章,我可以将文章链接在一起,a.outcomes << b但链接表只存储了结果 ID,而不是源 ID。
我究竟做错了什么?
我最终得到了这个工作。我改了名字——我不知道这是否重要。我确实在某处读到过,来源是一个愚蠢的名字,用于某些东西。
所以这是有效的:
我的架构
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
Run Code Online (Sandbox Code Playgroud)
我的文章模型
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
Run Code Online (Sandbox Code Playgroud)