Search code examples
ruby-on-railsrubyruby-on-rails-4rails-routingnested-resources

Rails: Restrict Nested Resource Path


I'd like to keep my nested resources within the context of its parent. Here's my code below:

routes.rb :

resources :categories do
  resources :subcategories
end

migration :

create_table "categories" do |t|
  t.string "name"
end

create_table "subcategories" do |t|
  t.string  "name"
  t.integer "category_id"
end

models :

class Categories < ActiveRecord::Base
  has_many :subcategories
end

class Subcategories < ActiveRecord::Base
  belongs_to :category
end

Here's my data:
Category id: [1, 2]
Subcategory id: [1..10], category_id: 1
Subcategory id: [11..20], category_id: 2

For my paths, /category/1/subcategory/[1..10] works perfectly fine. However, if I edit the url directly to /category/1/subcategory/[11..20], the subcategories still show even though they are under category id: 2.

I must be missing something in my code. Something tells me that's not how it's supposed to work. It should throw an error if you're entering in a subcategory id that isn't associated to its category_id.

How would I fix this?


Solution

  • As I don't see the controller method I suppose that the search is running only with one parameter (instead of necessary two), params[:id] (which is the id of the subcategory). As a result, you always get the subcategory with the provided id, but not within some (also provided) category id. You can do something like this to solve the issue you're struggling with :

    @data = Category.find(params[:category_id])
                    .subcategories
                    .find(params[:id])