通过 slug 和 id 查找

Lookup by slug and id

我目前在我的产品控制器显示操作中有以下内容:

@product = Spree::Product.active.where(slug: params[:id]).first!

这仅在传递 slug 时有效,我希望能够传递 id 或 slug 并使其起作用:

有点像:

Spree::Product.active.where(slug: params[:id]).first! || Spree::Product.active.where(id: params[:id]).first!

现在当我输入 products/foo-bar 时它起作用了,而不是当我输入 products/1

有办法吗?先感谢您。

.first!

找不到记录时引发错误。 尝试

Spree::Product.active.find_by(slug: params[:id]) || Spree::Product.active.find_by(id: params[:id])

如果第一个查询没有return值

,它将尝试第二个查询

最简单的方法是在 where 中搜索两者,如下所示:

Spree::Product.active.where("slug = :parameter OR id = :parameter", parameter: params[:id]).first!

这将找到 Spree::Product,其中 slugid 等于 params[:id]