【问题标题】:Delete associated record that isn't yet saved to db删除尚未保存到数据库的关联记录
【发布时间】:2015-07-13 08:17:33
【问题描述】:

所以我有一个 items 模型,它可以有很多 line_items

有些 line_items 存储在数据库中,但有些是在内存中创建、编辑和/或删除而没有被保存回来的

我的问题是,一旦我为内存中的项目创建了新的 line_item,我该如何删除它?

理想情况下,我应该能够通过它的类别 id 缩小 line_items 然后删除它

现在我有这个代码

line_items_for_removal = [5,6,7,8] #list of category ids to search through
item = Item.find(1)

    line_items_for_removal.each do |line_item|
      item.line_items.select{|x| x.category_id == line_item nil}.each{|x| item.destroy}
    end

这一切在选择正确的记录时都可以正常工作,但问题在于删除持久记录。

我已经尝试过删除和销毁,但除非记录被持久化,否则似乎都没有做任何事情

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    好的,所以通过将要删除的 line_item 作为参数传递给 delete 方法来解决这个问题,如下所示

     line_items = self.line_items
        line_items_for_removal.each do |item|
          line_items.select{|x| x.category_id = item}.each{|item| line_items.delete(item)}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-13
      • 1970-01-01
      相关资源
      最近更新 更多