rubyruby-on-rails-5nested-attributesaccepts-nested-attributes

Access childrens using where condition for nested attributes


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.


Solution

  • 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 }