1

I'm learning Ruby and Rails and trying to figure out the most correct path to go for my scenario regarding possibly namespacing as well as routing.

Say I have a 'Zoo' model as well as 'Species' model. I also need a relationship between them to tell what Species are in what Zoos (a Zoo has many Species, which will also have their own properties such as qty, location, etc)

I would like my routes to be like:

/zoo
/zoo/:id
...
/zoo/:zoo_id/species/
/zoo/:zoo_id/species/:id
...
/species
/species/:id

I have tried messing with modules, namespaces, route scopes, etc. I can't seem to get it how I'd like and think there has to be a better/natural way to do this. The problem is mainly due to the fact that I have a species model as well as a species model of zoo (I've tried namespacing to Zoo and creating a Zoo::Zoo and Zoo::Species classes, creating a ZooSpecies class, and adjusting routes for those scenarios, etc)

From an organizational standpoint, it would be great to be able to have a Zoo class as well as a Zoo namespace, to have Zoo::Species and such, but that is not possible.

What is the proper way to organize something like this?

Update: My current setup...

Zoo Module
Zoo::Zoo Class
Zoo::Species Class
Species Class

Routes:

resources :zoos, path: 'zoos' do
  resources :zoo_species, path: 'species', as: 'species', controller: 'zoo/species'
end

And a Zoo controller and a Zoo::Species controller. I feel like I'm getting closer to the desired result, but fighting against the framework more than I think I should. Still running into some issues properly setting up the relationships and paths, having to specify a lot of config values

4

2 に答える 2

0

リソースをネストするには:

resources :zoos do # /zoos(/:id)
  resources :species # /zoos/:zoo_id/species(/:species_id)
end

名前空間へ:

namespace :zoo do
  resources :posts # /zoo/posts(/:id)
end

その名前空間を作成する場合、クラス定義で app/controllers/zoo/posts_controller.rb を作成する必要があります:

class Zoo::PostsController < ApplicationController
  # ...
end

注: ネストされたリソースと名前空間は 2 つの異なるものです。ルーティングに関するRailsガイドは非常に読みやすいです。

于 2013-10-03T04:17:16.093 に答える