0
鉴于模型的has_many通过与现有的对象关联/ ActiveRecord的
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")
其结果将是与内容“你好”的组成,用文字标签“#hi”创建了。
然后我再创建一个构图。
Composition.create(content: "Goodmorning")
现在我不知道并且想要做的就是将它与现有的标签相关联,并带有文本“#hi”。
我该如何以最优雅的方式做到这一点?