我正在寻找一种基于它接收的params数组构建查询的简洁方法。为了给出一些上下文,用户可以选择过滤器以根据类别名称
返回所需的对象集class Category < ActiveRecord::Base
has_many :bike_categories
has_many :bikes, through: :bike_categories
end
class BikeCategory < ActiveRecord::Base
# Holds bike_id and category_id to allow multiple categories to be saved per image, as opposed to storing an array of objects in one DB column
belongs_to :bike
belongs_to :category
end
class Bike < ActiveRecord::Base
has_many :bike_categories, dependent: :destroy
has_many :categories, through: :bike_categories
end
所以在我的案例中过滤自行车的类别
(Mens, Womens, Mountain Bike, Hybrid).
自行车可以有超过1个类别
所以用户可以选择男装,但也想看Mens Mountain Bikes,在这种情况下我只想要拥有Mens和Mountain Bikes类别的自行车
目前我有
class Bike < ActiveRecordBase
def self.search(params)
bikes = joins(:categories)
bikes = bikes.where(categories: { name: params[:name] }) if params[:name].present?
end
end
我了解我可以将查询链接到.where(param: value1).where(param: value2)
或者数组可以通过
传递bikes.where(categories: { name: [params[:name]] }) if params[:name].present?
如果我没记错的话,会发表IN
语句。
我怎样才能构建此查询以便获得我需要的结果
由于
更新
例如,我有以下设置
Bike
id: 1 title: 'Bike 1'
category
id: 1 name: 'Mens'
id: 2 name: 'Womens'
id: 3 name: 'Mountain Bike'
id: 4 name: 'Hybrid'
bike_categories
id: 1 bike_id: 1 :category_id: 2
id: 2 bike_id: 1 :category_id: 2
所以我有一个有两个类别的自行车Womens, Mountain Bike
,我想找到那个记录