构建Rails关联

时间:2014-01-25 19:17:11

标签: ruby-on-rails ruby-on-rails-4 associations rails-activerecord rails-models

我应该如何构建这个Rails关联?

问题

因此,用户基本上可以创建数据集,然后创建数据集。我希望用户能够创建项目,并标记包含多个项目的数据集或图形。如果数据集标记有项目,则不应自动标记属于它的所有图形(数据集)。

我是一个Rails协会noob。阅读文档听起来我可以做这样的事情。

  1. “dataset”has_many“graph”。
  2. “project”has_many“数据集”和“图表”。
  3. “dataset”has_many“projects”。
  4. “graph”has_many“projects”。
  5. 解决方案:(这是正确的吗?)

    4个模型:Dataset, Graph, Project, ProjectContent

    对于#1:

    Dataset has_many Graphs
    Graph belongs_to Dataset
    

    对于#2:

    Project has_many datasets, through: :project_content
    Project has_many graphs, through: :project_content
    

    对于#3:

    Dataset has_many projects, through: project_content
    

    对于#4:

    Graph has_many projects, through: project_content
    

1 个答案:

答案 0 :(得分:1)

这对我来说是“多态”,几乎是默认用例;)

标签型号:

belongs_to :taggable, :polymorphic => true
belongs_to :project

项目模型:

has_many :tags
has_many :datasets, :through => :tags, :source => :taggable, :source_type => 'Dataset'
has_many :graphs, :through => :tags, :source => :taggable, :source_type => 'Graph'

图表模型:

belongs_to :dataset
has_many :tags, :dependent => :destroy
has_many :projects, :as => :taggable

数据集模型:

has_many :graphs
has_many :tags, :dependent => :destroy
has_many :projects, :as => :taggable

如果您不想使用多态模型,那么您的方法似乎是正确的。

相关问题