Search code examples
ruby-on-railsruby-on-rails-4ruby-on-rails-5friendly-id

Find resource by slug in nested resource in rails


I have following routes

 resources :shops do
    resources :categories
  end

And when I visit this url:

http://localhost:3000/shops/rabin-shop/categories

I first want to find the shop by using slug 'rabin-shop', then I can filter the categories of products that belong to that shop. In my controller I have tried to implement

    def find_shop
       @shop = Shop.find(params[:slug])
    end

But this is not working. I know this is not how to find in nested resource. I am using friendly_id gem . I cannot do something like current_user.shop because I want the page to be accessed even when the user is not logged in.


Solution

  • If you are using the freindly_id gem, this is how you find a record by it's slug :

     def find_shop
       # params[:shop_id] if nested
       @shop = Shop.friendly.find(params[:id])
     end