查询nil属性时,.where返回nil

时间:2014-01-27 16:32:28

标签: sql ruby-on-rails ruby

我正在尝试通过其属性使用.where查找对象(Variant),如果没有参数为nil,则查询有效,否则返回任何内容。这是我的代码:

product.product_options.blank? ? options = [nil] : options = product.product_options
product.product_sides.blank? ? sides = [nil] : sides = product.product_sides
product.product_sizes.blank? ? sizes = [nil] : sizes = product.product_sizes

valid_variants = []

sides.product(sizes, options).each do |side, size, option|
    side.blank? ? side_id = nil : side_id = side.id
    size.blank? ? size_id = nil : size_id = size.id
    option.blank? ? option_id = nil : option_id = option.id

    valid_variants << product.variants.where(product_size_id: size_id, product_side_id: side_id, product_option_id: option_id).first
end

在这种情况下,product.variants确实包含与side,size和option id匹配的变体,但valid_variants为空。

以下是product.variants的内容:

{"id"=>1, "product_side_id"=>nil, "product_size_id"=>1, "product_id"=>1, "created_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "updated_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "product_option_id"=>1}
{"id"=>2, "product_side_id"=>nil, "product_size_id"=>1, "product_id"=>1, "created_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "updated_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "product_option_id"=>2}
{"id"=>3, "product_side_id"=>nil, "product_size_id"=>2, "product_id"=>1, "created_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "updated_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "product_option_id"=>1}
{"id"=>4, "product_side_id"=>nil, "product_size_id"=>2, "product_id"=>1, "created_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "updated_at"=>Mon, 27 Jan 2014 16:28:46 UTC +00:00, "product_option_id"=>2}

以下是使用product.variants.where时的valid_variants的内容(product_size_id:size_id,product_side_id:side_id,product_option_id:option_id)。第一次

[nil, nil]

以下是使用product.variants.where时的valid_variants的内容(product_size_id:size_id,product_side_id:side_id,product_option_id:option_id)

[#<ActiveRecord::AssociationRelation []>]

1 个答案:

答案 0 :(得分:0)

您在每次迭代时重置valid_variants数组。将valid_variants = []移到循环之外:

valid_variants = []
sides.product(sizes, options).each do |side, size, option|
    side_id = side.blank? ? nil : side.id
    size_id = size.blank? ? nil : size.id
    option_id = option.blank? ? nil : option.id

    valid_variants << product.variants.where(product_size_id: size_id, product_side_id: side_id, product_option_id: option_id).first
end

更新了您的side_idsize_idoption_id初始化。