English 中文(简体)
Ruby On Rails的关系——一个到多个
原标题:
  • 时间:2009-05-10 21:10:35
  •  标签:

我开始ROR,但在这里我想实现的东西。我有两个项目我想关联:问题和人。每一个问题都有很多人。我想创造人与问题分开,后来可以联系他们。

For example, I may create: Bill Clinton Barack Obama

I may create the matters: Global warming War on terror

我希望能够把用户比尔•克林顿和巴拉克•奥巴马(Barack Obama)这两个问题。有人能告诉我一个教程,教我如何能做到这一点吗?

问题回答

我认为<代码> has_and_belongs_to_many > < /代码是用RoR社会越来越少了。虽然仍然支持,我认为这是现在更常见的一个中间模型(在你的案子类似<代码> PoliticianMatter > < /代码)加入您的<代码>政治家< /代码>和<代码> < / >代码模型。

那么你的<代码> politician_matter < /代码>表将PK,一个<代码> politician_id < /代码>和<代码> matter_id > < /代码。

那么你就

class PoliticanMatter < ActiveRecord::Base
  belongs_to :politician
  belongs_to :matter
end

这种方法的优点是,如果需要有未来的政治家的属性- > (e物质的关系。g的重要性,最后发生日期)你有一个模型,提供——<代码> has_and_belongs_to_many > < /代码不会支持增加这些额外的属性。

您也可以直接访问许多许多关系从政治家和物质模型

class Politician < ActiveRecord::Base
  has_many :politician_matters
  has_many :matters, :through => :politician_matters
end

class Matter < ActiveRecord::Base
  has_many :politician_matters
  has_many :politicians, :through => :politician_matters
end

你需要一个many2many这些两个实体之间的关系。

  • A matter can be studied by many people
  • A person can studie several matters

Rails使用<代码> has_and_belongs_to_many > < /代码辅助。你会发现更多关于在文档和许多博客!

< a href = " http://www.railsbrain.com/api/rails-2.3.2/doc/index.html?一个= M001888&name = has_and_belongs_to_many nofollow noreferrer“rel = > has_and_belongs_to_many助手< / >

class Politician < ActiveRecord::Base
  has_and_belongs_to_many :tasks
end

class Task < ActiveRecord::Base
  has_and_belongs_to_many :politicians
end

What you need are 3 tables: politicians, tasks and politicians_tasks (having the two columns politician_id and task_id, no primary key)

Hope this helps Seb





相关问题
热门标签