【问题标题】:has_many through association with existing object / ActiveRecordhas_many 通过与现有对象/ActiveRecord 关联
【发布时间】:2012-11-01 02:36:09
【问题描述】:

给定模型

class Composition < ActiveRecord::Base
  attr_accessible :content

  has_many :compositions_tags
  has_many :tags, :through => :compositions_tags

end

class Tag < ActiveRecord::Base
  attr_accessible :text

  has_many :compositions_tags
  has_many :compositions, :through => :compositions_tags

  validates_uniqueness_of :tag, only: [:create, :update], message: "already taken"
end

class CompositionsTag < ActiveRecord::Base
  belongs_to :composition
  belongs_to :tag
end

现在,例如我这样做

Composition.create(content: "Hello").tags.create(text: "#hi")

结果将是一个内容为“Hello”的合成和一个带有文本“#hi”的标签已创建。

然后我再次创建一个合成。

Composition.create(content: "Goodmorning")

现在我不知道并且想要做的是将它与现有的标签相关联,带有文本“#hi”。

如何以最优雅的方式做到这一点?

【问题讨论】:

    标签: ruby-on-rails activerecord associations has-many-through


    【解决方案1】:

    如果您对创建记录的顺序很灵活,您可以创建标签,然后在一行中创建两个组合:

    Tag.create(text: "#hi").compositions.create([{content: "Goodmorning"},{content: "Hello"}])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多