使用嵌套条件的where条件访问子项

问题描述 投票:0回答:1

我设置了以下关系,仪表板过滤器值有一个名为filter_type的列,其值可以为1或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

before_save回调中,当我使用self.dashboard_filter_values.inspect时,将打印ActiveRecord::Associations::CollectionProxy

但是self.dashboard_filter_values.where(:filter_type => 0) 打印任何内容,即使有满足条件的记录。

before_save回调中,如何使用where条件过滤所需的值。

在这方面的任何帮助都将非常棒。谢谢。

ruby ruby-on-rails-5 nested-attributes accepts-nested-attributes
1个回答
0
投票
我会说您有2个选择:

将其转换为after_save

    改为使用Enumerable#map
  • Rails.logger.info self.dashboard_filter_values.map { |filter| filter.filter_type == 1 }
  • © www.soinside.com 2019 - 2024. All rights reserved.