Rails routes.rb syntax

I searched and searched, and I can’t find a page that talks about route.rb syntax in Rails 3. There are recommendations, reviews, and even advanced examples, but why not a page that shows the exact syntax of each keyword? This page

http://www.engineyard.com/blog/2010/the-lowdown-on-routes-in-rails-3/

contains many additional examples, but does not take time to discuss the behavior of all the examples given. I would appreciate it if someone could point me to a page that breaks the syntax of .rb routes.

Here is the problem I'm trying to solve. I have two models, modelA and modelB. The relationship is modelA has_many modelB, and modelB belongs to model A. I created a controller for modelB in the modelA namespace. So in the rails application folder I have

app/controllers/modelA_controller.rb app/controllers/modelA/modelB_controller.rb 

I want my routes to be like this:

 http://localhost:3000/modelA/:modelA_id/modelB/ [index] http://localhost:3000/modelA/:modelA_id/modelB/:modelB_id [show] etc. 

I tried the following in routes.rb and none of them work:

 resources :modelA do resources :modelB end -- resources :modelA do member do resources :modelB end end -- namespace :modelA do resources :modelB end -- match '/modelA/:modelA_id/modelB/action', :to => '/modelA/modelB#action' 

I know that some of the things I tried are clearly wrong, but when you spent 2 days on one problem, everything goes!

+7
source share
1 answer

The reason that no one has a “definitive” guide to routing syntax is that it is quite flexible, so you could probably write a few chapters on just one issue. However, I would recommend: http://guides.rubyonrails.org/routing.html

From your question, it looks like you are in the modelB namespace under modelA , but also want the id for modelA be inside the route itself.

So, if your ModelBController looks something like this:

 class ModelA::ModelBController < ApplicationController # controller code here end 

then you can just do:

 resources :modelA do resources :modelB, :module => :modelA end 

However, are you sure you want to skip the controller namespace? If you just need nested resources, like the typical has_many relation, you don’t need to place modelB names under modelA .

Instead, you will have:

 /app /controllers /modelA # some files /modelB # some files 

And your modelB controller:

 class ModelBController < ApplicationController # controller code here end 

Then you could do

 resources :modelA do resources :modelB end 
0
source

All Articles