0

There is a join table with three columns: id, product_a_id, product_b_id

class ProductConnection < ActiveRecord::Base
  belongs_to :product_a, class_name: :Product
  belongs_to :product_b, class_name: :Product    
end

I would like to filter the table by a specific product regardless in which column the product id is contained. How can I write a named scope which respects that a product can be nil? The following draft is inspired by a post by Zack Holman though it does not work:

scope :find_by_product, \
  lambda {|p| p.nil? ? { \
    where(["product_a_id = ? OR product_b_id = ?", p.id, p.id]) : {} \
  }

Then I would like to know how I can delete all products returned in the ActiveRecord::Relation?

4

1 回答 1

1

听起来问题在于find_by_product当传入的产品为零时如何使您的范围工作?我认为你的花括号有点混乱。无论哪种方式,如果这有帮助,我会这样写:

ProductConnection

scope :for_product, ->(product) {
  if product_id = product.try(:id)
    where(arel_table[:product_a_id].eq(product_id).
            or(arel_table[:product_b_id].eq(produt_id))
  end
}

然后,一旦可行,您只需在作用域上调用destroy_all即可销毁所有记录。

ProductConnection.for_product(my_product).destroy_all

还有delete_all,如果您真的不希望 ActiveRecord 回调包含在destroy.

于 2013-09-08T21:45:02.853 回答