Remove Element from an ActiveRecord-hash without d

2019-09-16 00:28发布

问题:

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