过滤器有多个直通模型
Filter Has Many Through Model
我是 RoR 的新手。我正在建立电子商务网站,其中我有两个模型产品和类别如下:
Products : has_many :categories_products, dependent: :destroy
has_many :categories, through: :categories_products
Categories: has_many :categories_products
has_many :products, through: :categories_products
Categories_products: belongs_to: products, belongs_to: categories
我的网站有类别的大型菜单。我的意图是单击这些类别中的任何一个并获取属于它的所有产品。到目前为止,我只能得到 category_id,因为我正在使用参数来获取类别。
if params[:category]
@categoryproducts = :category.products.all.paginate(page: params[:page], per_page: 20)
else
redirect_to root_url
end
关于使用上述方法
undefined method `products' for :category:Symbol
我在网上搜索过,大部分都说用join table。预先感谢您的帮助。
如果category_id
在参数中传递,你可以这样做:
if params[:category_id]
@products = Product.joins(:categories).where(
categories: { id: params[:category_id] }
).all.paginate(page: params[:page], per_page: 20)
else
redirect_to root_url
end
我是 RoR 的新手。我正在建立电子商务网站,其中我有两个模型产品和类别如下:
Products : has_many :categories_products, dependent: :destroy
has_many :categories, through: :categories_products
Categories: has_many :categories_products
has_many :products, through: :categories_products
Categories_products: belongs_to: products, belongs_to: categories
我的网站有类别的大型菜单。我的意图是单击这些类别中的任何一个并获取属于它的所有产品。到目前为止,我只能得到 category_id,因为我正在使用参数来获取类别。
if params[:category]
@categoryproducts = :category.products.all.paginate(page: params[:page], per_page: 20)
else
redirect_to root_url
end
关于使用上述方法
undefined method `products' for :category:Symbol
我在网上搜索过,大部分都说用join table。预先感谢您的帮助。
如果category_id
在参数中传递,你可以这样做:
if params[:category_id]
@products = Product.joins(:categories).where(
categories: { id: params[:category_id] }
).all.paginate(page: params[:page], per_page: 20)
else
redirect_to root_url
end