0

Given models

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

Now, for example I do

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

The result would be is a Composition with content "Hello" and a Tag with text "#hi" having created.

Then I create again a Composition.

Composition.create(content: "Goodmorning")

Now what I don't know and wanted to do is associate that as well to the existing Tag with text "#hi".

How do I do that in the most elegant way?

neilmarion
  • 2,372
  • 7
  • 21
  • 36

1 Answers1

1

If you are flexible on the order in which you create your records, you can create the tag and then create the two compositions in one line:

Tag.create(text: "#hi").compositions.create([{content: "Goodmorning"},{content: "Hello"}])
cdesrosiers
  • 8,862
  • 2
  • 28
  • 33