1

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?

potashin
  • 44,205
  • 11
  • 83
  • 107
leejay100
  • 221
  • 1
  • 2
  • 12

1 Answers1

0

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])
potashin
  • 44,205
  • 11
  • 83
  • 107
  • I'll have the try that. But even then, I'm not sure this fixes the problem of editing the url directly, does it? – leejay100 Apr 05 '15 at 00:31
  • @leejay100: As a matter of fact, it does. You can imagine it as a chain of checks: let's say, the uri is `/category/1/subcategory/15`. So, at first, the method finds all categories with `id = 1` (as you can see, you have only one). Then it finds all it's `subcategories` (`[1..10]`), then it tries to find the subcategory with the `id = 15` within this collection, but there is none of it, hence there is nothing to display. – potashin Apr 05 '15 at 00:37
  • 1
    Ah, I see. I would just put this in the show method. Thanks @notulysses – leejay100 Apr 05 '15 at 00:45