When I do:
apartments = Apartment.where(apart_params).delete_if{|x| x.floor == x.max_floor }
Ruby's array method delete_if on Active record Relation object results in
NoMethodError (undefined method `delete_if' for #<Apartment::ActiveRecord_Relation:0x00000006d84ea0>
Did you mean? delete
delete_all):
I don't understand why it happens - this object seems to respond like a plain array...
Is there any smarter alternative except using plain each do block?
Maybe you can give an advise on making smart SQL (postgres) query to reject those apartments which are on the last floor?
The relation can be converted to an array and then delete_if can be called:
Apartment.where(apart_params).to_a.delete_if {|x| x.floor == x.max_floor }
About a smarter way, it depends if the floor and max_floor methods are columns. If so, then:
Apartment.where(apart_params).where.not("floor = max_floor")
I would suggest switching your apartments assignment to the following:
apartments = Apartment.where(apart_params).map{|x| x.floor == x.max_floor ? x.delete : x }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With