Has_many通过Association Rails和自己的模型

时间:2014-09-08 22:35:55

标签: ruby-on-rails ruby activerecord associations

我已经彻底阅读了this stack overflow question.

我仍然无法尝试将其应用于我自己的情况。我有一个文章模型和一个文章关系模型,用于通过因果关系将文章绑定到自己

   create_table "article_relations", force: true do |t|
     t.integer  "cause_id"
     t.integer  "effect_id"
     t.integer  "user_id"
     t.datetime "created_at"
     t.datetime "updated_at"   end

   add_index "article_relations", ["user_id"], name:
 "index_article_relations_on_user_id", using: :btree

  create_table "articles", force: true do |t|
    t.string   "code"
    t.text     "description"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

理想情况下,我希望能够做到:

a = Article.find(...)
a.causes 
  # [b,c,d]
a.effects 
  # [e,f,g]

e = Article.find(...)
e.causes 
  # [a,c,d]
e.effects 
  # [x,y,z]

在我的模特中,我添加了:

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :effects, :through => :article_relations, :source => :effect
  has_many :causes, :through => :article_relations, :source => :cause

end

和article_relation类:

class ArticleRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :cause, :class_name => :Article
  belongs_to :effect, :class_name => :Article
end

我很确定我的架构设置正确,但我不确定我的模型是什么。我可以添加什么以便能够实现上述期望的行为?是否可以通过以下方式级联删除:dependent =&gt;破坏?

1 个答案:

答案 0 :(得分:0)

确实,您需要:Article

中的首都'Article'ArticleRelation

此外,我能够成功创建关系:

class ArticleRelation < ActiveRecord::Base
  belongs_to :user
  belongs_to :cause, :class_name => :Article
  belongs_to :effect, :class_name => :Article
end

并在文章模型中:

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :effects, :through => :effect_relations, :foreign_key => :cause_id
  has_many :causes, :through => :cause_relations, :foreign_key => :effect_id
  has_many :cause_relations, :class_name => :ArticleRelation, :foreign_key => :effect_id
  has_many :effect_relations, :class_name => :ArticleRelation, :foreign_key => :cause_id
end

希望这可以帮助其他人遇到这个问题。现在我可以执行a.causes并返回一个填充了文章类型的数组!