Rails - 删除未保存的关联记录 [英] Rails - Deleting unsaved associated records

查看:36
本文介绍了Rails - 删除未保存的关联记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含许多文章的用户模型.

Lets say I have a user model that has many articles.

如果我多次调用 user.articles.new,我将有许多与用户关联的未保存的文章对象.当您运行 user.articles 时,它们是可见的.调用 user.save 将保存所有这些未保存的记录.

If I call user.articles.new many times I will have many unsaved article objects associated with the user. They are visible when you run user.articles. Calling user.save will save all of this unsaved records.

如何删除未保存的记录?我打算调用 user.save 但我不希望那些未保存的记录存在

How can I delete unsaved records? I plan on calling user.save but I don't want those unsaved records to be there

推荐答案

我使用以下解决方法 before_validation :remove_blank_articles!:

I use the following workaround before_validation :remove_blank_articles!:

class User
  has_many :articles

  validates_associated :articles

  before_validation :remove_blank_articles!

  private
    def remove_blank_articles!
      self.articles = articles - articles.select(&:blank?)
      true
    end
end

class Article
  belongs_to :user

  validates_presence_of :title, :body

  def blank?
    title.blank? and body.blank?
  end
end

这篇关于Rails - 删除未保存的关联记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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