neo
neo

Reputation: 4116

Lookup by slug and id

I currently have the following in my products controller show action:

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

This only works when slug is passed, I want to be able to pass in id or slug and for it to work:

kinda like:

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

Right now when I type products/foo-bar it works, not when I type products/1

Is there a way to do this? Thank you in advance.

Upvotes: 3

Views: 1686

Answers (2)

ptd
ptd

Reputation: 3053

The simplest way would be to search for both in a where like so:

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

This will find the Spree::Product where either the slug or id is equal to the params[:id].

Upvotes: 1

Stanislav Mekhonoshin
Stanislav Mekhonoshin

Reputation: 4386

.first!

Raises error when record not found. Try

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

It'll try second query if first does not return value

Upvotes: 3

Related Questions