代码之家  ›  专栏  ›  技术社区  ›  tehfailsafe

轨道嵌套与first_or_create的关联

  •  0
  • tehfailsafe  · 技术社区  · 13 年前

    我有一个 comic_books 表中有许多问题,每个问题都有一个 author and illustrator ,当前仅存储为字符串。使用 has_many:through 对于漫画书来说,发行效果很好,现在我正试图找出如何为作者和插图画家添加关联。

    问题是作者和插图画家有时是同一个人。如果你点击一个插画师,我想看看他/她写的或画的具体问题。如果我设置 has_one belongs_to association 我只会得到插图或作者的卷结果,但我希望两者都来自同一个“创作者”。

    因此,我尝试了 creator 表,但我不知道如何放置关联。我想要一个创建者表,用于存储 name ,和 creator_id 无论是作家还是插画家。

    那我想打电话

    issue.illustrator.first_or_create!('bob smith')
    

    但这是不对的。 我不想要独立的插画师和作家表,因为他们每个人都有相同的名字。我需要把它进一步抽象出来,但我似乎想不出来。

    我想我想制作一个新的创作者记录,如果它不存在并存储 创建者id 插入到illustrator表中,这样我就可以引用issue.intellator.name,但name值实际上在creator表中。。。

    有没有更好的方法来完成整个任务?

    1 回复  |  直到 12 年前
        1
  •  1
  •   zkcro    13 年前

    关于你试图指派一位插画师,你可能想做这样的事情:

    issue.illustrator = Illustrator.first_or_create(name: "Bob Smith")
    

    这取决于你使用的型号。我有点迷失了你有什么模型,以及你是如何构建它们的关联的。

    我处理这种情况的方法可能是使用 Creator 类,并使用第三个交叉引用模型(例如, Involvement )将其链接到特定 Issues ,并具体说明他们在第三个模型中的角色。关联看起来是这样的(忽略 Comic ,因为听起来你是通过 Issue ):

    class Issue < ActiveRecord::Base
      has_many :involvements
      has_many :creators, through: :involvements
      ...
    end
    
    class Creator < ActiveRecord::Base
      has_many :involvements
      has_many :issues, through: :involvements
      ...
    end
    
    class Involvement < ActiveRecord::Base
      belongs_to :issue
      belongs_to :creator
    
      # This model would then have an extra property to store the type of involvement
      # ie. author, illustrator, author/illustrator
      attr_accessible :type, ...
    end
    

    (我倾向于 type 上的属性 参与 一个位掩码整数,所以它可能是 1 对于作者来说, 2 插图画家,以及 3 作者/插图画家。)

    通过这种方式,您可以添加 造物主 问题 具有以下内容:

    inv = Issue.involvements.create(type: ...) # Whatever's appropriate
    inv.creator = Creator.find_or_create('Bob Smith')