Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Single Resource as Nested Resource of Two Other Resources

I have a business, a catalog and a product resource.

A business has a catalog and a number of products.

A catalog will always belong to a business.

A product may or may not be under a catalog.

The products table both has catalog_id and business_id.

How will I form the route so that I can allow a product without a catalog and a product belonging to a catalog, i.e., these URLs:

  • businesses/:business_id/catalogs/:catalog_id/products/:id
  • businesses/:business_id/products/:id

I have already allowed the latter using this:

resources :businesses do
    resources :catalogs

    resources :products do
      resources :images
      end
  end

how do I modify it to allow the first URL?

I know I'm just missing something simple, feel free to close this and refer to a duplicate if there is one.

Thanks a lot!

like image 834
yretuta Avatar asked Nov 26 '25 10:11

yretuta


1 Answers

Well, you were almost there:

resources :businesses do
    resources :catalogs do
      resources :products do
        resources :images
      end
    end

    resources :products do
      resources :images
    end
end

The same way you did for businesses/products you can also do for businesses/catalogs/products, there is no difference, just nest the resources.

like image 149
Maurício Linhares Avatar answered Nov 29 '25 18:11

Maurício Linhares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!