活动记录的has_many:通过删除一个相关的记录 [英] Active Record has_many :through remove one associated record

查看:129
本文介绍了活动记录的has_many:通过删除一个相关的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是我的一部分,一个非常基本的监督,但我似乎无法记得一个简单的方法,通过删除两者之间的对象加入一个协会的has_many:通过 。 IE浏览器:

 类照片
  的has_many:标签,:通过=> :的Tagging
  的has_many:的Tagging,:依赖=> :破坏
结束

类标签
  的has_many:照片:通过=> :的Tagging
  的has_many:的Tagging,:依赖=> :破坏
结束

一流的Tagging
  belongs_to的:照片
  belongs_to的是:标签
结束
 

如果您有两个对象,标记照片,你可以将它们这样做的话联系起来:

  photo.tags<<标签
 

那么,有没有一个同样简单相反呢?即:

  photo.tags.remove标签
 

解决方案

这就是你想要的:

  photo.tags.delete(标记)
 

This may be a very basic oversight on my part, but I can't seem to recall a simple method for removing an association between two objects joined via has_many :through. IE:

class Photo
  has_many :tags, :through => :taggings
  has_many :taggings, :dependent => :destroy
end

class Tags
  has_many :photos, :through => :taggings
  has_many :taggings, :dependent => :destroy
end

class Taggings
  belongs_to :photo
  belongs_to :tag
end

If you have two objects, tag and photo, you can associate them just by doing this:

photo.tags << tag

So, is there an equally simple opposite to this? ie:

photo.tags.remove tag

解决方案

here's what you want:

photo.tags.delete(tag)

这篇关于活动记录的has_many:通过删除一个相关的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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