【问题标题】:Active Record has_many :through remove one associated recordActive Record has_many:通过删除一条关联记录
【发布时间】:2012-10-24 08:28:08
【问题描述】:

这可能是我的一个非常基本的疏忽,但我似乎想不起一个简单的方法来删除通过has_many :through 连接的两个对象之间的关联。即:

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

如果您有两个对象,tagphoto,您可以这样做来关联它们:

photo.tags << tag

那么,有没有一个同样简单的反面?即:

photo.tags.remove tag

【问题讨论】:

    标签: ruby-on-rails activerecord has-many-through


    【解决方案1】:

    这就是你想要的:

    photo.tags.delete(tag)
    

    【讨论】:

    • 请注意,这不会在连接模型上触发 before_destroyafter_destroy 回调 - 如果需要,请使用 destroy 代替 delete
    猜你喜欢
    • 2012-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    相关资源
    最近更新 更多