通过与现有的对象关联的has_many / ActiveRecord的 [英] has_many through association with existing object / ActiveRecord

查看:123
本文介绍了通过与现有的对象关联的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")

其结果将是一个成分与内容的Hello,并与文字一个变量#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")

现在是什么我不知道,想要做的就是联想的以及现有的标记文本#hi。

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?

推荐答案

如果您是灵活的,你创建的记录的顺序,您可以创建标签,然后在同一行创建两个组成:

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

这篇关于通过与现有的对象关联的has_many / ActiveRecord的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆