has_many through association with existing object / ActiveRecord

人走茶凉 提交于 2019-12-24 18:15:53

问题


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?


回答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"}])


来源:https://stackoverflow.com/questions/13170183/has-many-through-association-with-existing-object-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!