Remove Element from an ActiveRecord-hash without delete on DB

守給你的承諾、 提交于 2019-12-13 03:39:11

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/15281935/remove-element-from-an-activerecord-hash-without-delete-on-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!