我目前在我的产品 Controller 显示操作中有以下内容:
@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])
如果第一次没有返回值,它会尝试第二次查询
关于ruby-on-rails - 通过 slug 和 id 查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28303965/