0
嵌套範圍中我有2個範圍:with_category和simple_search。他們每個人都很好地獨立工作,但是我無法得到我需要的東西。與軌道4
product.rb
has_many :categorizations, :dependent => :destroy
has_many :categories, :through => :categorizations
scope :with_category, lambda { |category_slug|
return {} if category_slug.blank?
joins(:categorizations => :category).where('categorizations.category_id = ?', Category.find_by_slug(category_slug).id).uniq
}
scope :simple_search, lambda { |query|
return {} if query.blank?
where('"products"."name" ~* ? OR "products"."description" ~* ?', query, query)
}
products_controller.rb
def index
@products = Product.with_category(params[:category])
.simple_search(params[:query])
.paginate(:page => params[:page], :per_page => 10)
end
當我去localhost:3000/products?category=apple-laptops
我想抓住當前類別中的所有產品。相反,這是我with_category的範圍被忽略,我能看到的所有產品。不知道爲什麼會發生這種情況。
從我的日誌:
Product Load (0.9ms) SELECT "products".* FROM "products" LIMIT 10 OFFSET 0
Category Load (0.7ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 2]]
Category Load (0.8ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 4]]
Category Load (0.7ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 10]]
Category Load (0.8ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 5]]
Category Load (0.7ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 18]]
Category Load (0.7ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 1]]
Category Load (0.8ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 3]]
Category Load (0.7ms) SELECT "categories".* FROM "categories" INNER JOIN "categorizations" ON "categories"."id" = "categorizations"."category_id" WHERE "categorizations"."product_id" = $1 [["product_id", 15]]
它的工作原理!非常感謝你! 也許你有一些想法,爲什麼我的代碼不工作,因爲它應該是? – MikeAndr
我想,從範圍返回'{}'正在打破這個鏈條。所以在這個返回之後,鏈條重新開始並且你之前的方法被忽略。 –
我明白了......再次感謝您! – MikeAndr