从ActiveRecord-Hash中删除元素而不删除数据库 [英] Remove Element from an ActiveRecord-hash without delete on DB

查看:198
本文介绍了从ActiveRecord-Hash中删除元素而不删除数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  all_tickets = Ticket.find(:all)

all_tickets.each do | at |
如果在条件下
all_tickets.delete(at)
end
end

使用这段代码,我从数据库中删除了at元素,但是我只想从all_tickets ActiveRecord-Hash中删除at元素,当条件为真时。



感谢您的帮助

解决方案

此解决方案已被转换为NOT暗示。总之,抓住票据,循环它们,如果条件成立,从属性中删除特定的键。最后,用这些属性生成一个新的票据实例(不记录)。

我了解情况是一件外部事情,但我会建议将attr_accessor添加到可能会出现此情况的对象上。我会在视图中利用这一点,以便不依赖于某个特定领域的存在或缺失来决定如何交付。我在这里做了一些假设,但解决方案让我对需要这种类型的操作的功能感到好奇。祝你好运。

  all_tickets = Ticket.find(:all)
processed_tickets = []
all_tickets.each do |票|
attributes = ticket.attributes
attributes.delete(:some_key)if some_condition?
processed_tickets<< Ticket.new(属性)
结束


how can i do this?

all_tickets = Ticket.find(:all)

all_tickets.each do |at|
   if at "a condition"
      all_tickets.delete(at)
   end
end

With this code i delete the at-element from database, but i only want to remove the at-element from the all_tickets ActiveRecord-Hash when the "a condition" is true.

Thanks for Help

解决方案

This solution has been converted to NOT use sql per your hint. In short, grab the tickets, loop over them and if the condition is true, delete the particular key from the attributes. Finally, generate a new ticket instance (not record) with these attributes.

I understand the condition is an outside thing, but I would suggest alternatively to add an attr_accessor onto the object that would take on the condition. I would leverage this in the view so as to not rely on the presence or absence of a given field to determine how it's delivered. I'm making a number of assumptions here, but the solution makes me curious about the feature requiring this type of operation. Best of luck.

all_tickets = Ticket.find(:all)
processed_tickets = []
all_tickets.each do |ticket|
  attributes = ticket.attributes
  attributes.delete(:some_key) if some_condition?
  processed_tickets << Ticket.new(attributes)
end

这篇关于从ActiveRecord-Hash中删除元素而不删除数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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