1

I have the following relationship set, dashboard filter values have a column called filter_type which can have value 1 or 0.

class DashboardFilterValue < ApplicationRecord
  belongs_to :dashboard_filter
end
class DashboardFilter < ApplicationRecord
  has_many :dashboard_filter_values, dependent: :destroy
  accepts_nested_attributes_for :dashboard_filter_values
  before_save :check_parameter_length

  def check_parameter_length
    Rails.logger.info self.dashboard_filter_values.inspect #prints the ActiveRecord::Associations::CollectionProxy
    Rails.logger.info self.dashboard_filter_values.where(:filter_type => 0) #does not print anything
  end
end

In the before_save callback, When I use self.dashboard_filter_values.inspect, this prints ActiveRecord::Associations::CollectionProxy.

But self.dashboard_filter_values.where(:filter_type => 0) does not print anything, even when there are records which satisfy the condition.

In the before_save callback, how can I use the where condition to filter values that I want.

Any help in this would be really great. Thanks.

noname
  • 565
  • 6
  • 23
opensource-developer
  • 2,826
  • 4
  • 38
  • 88

1 Answers1

2

I believe this is not working because of the before_save action. When you use where it is performing a database query, but because you are querying the database before it saves, nothing is returned.

I would say you have 2 options:

  1. Convert it to an after_save
  2. Use Enumerable#select instead:
Rails.logger.info self.dashboard_filter_values.select { |filter| filter.filter_type == 1 }
Trinculo
  • 1,950
  • 1
  • 17
  • 22
  • Thanks @Trinculo, that makes sense. I will go with your approach 2, as i want to invalidate the records in case a condition fails. i think with after_create it would be a bit tricky. – opensource-developer Nov 27 '19 at 14:56
  • 2
    I'm guessing you mean [`Enumerable#select`](https://ruby-doc.org/core-2.6.5/Enumerable.html#method-i-select), not [`Enumerable#map`](https://ruby-doc.org/core-2.6.5/Enumerable.html#method-i-map). `dashboard_values.select { |dashboard_value| dashboard_value.filter_type == 0 }` – 3limin4t0r Nov 27 '19 at 14:57
  • Yes, I ended up using select. Thanks for awesome help guys. – opensource-developer Nov 27 '19 at 15:24