you786
you786

Reputation: 3540

Getting a namespace inside of a resource with Rails 3 routing

I have a book model with all sorts of routes defined for it:

resources :books do
    member do
      get 'printable_version'
    end
    collection do
      get 'search'
      get 'recently_added'
    end
    resources :pages do
      collection do
        get 'new'
        get 'edit_all'
        post 'update_all'
      end
    end
  # I put a namespace declaration here 
  # namespace :marketing do 
  #   get 'mini_flyer'
  # end
  end

What I'd like to have now is a "Marketing" "subdirectory", meaning I'd like to be able to access routes like this:

/books/24/marketing/mini_flyer or /book/10/marketing/large_flyer

I attempted to put a namespace into the resource block but this is what I get from rake routes:

book_marketing_mini_flyer GET    /books/:book_id/marketing/mini_flyer(.:format) marketing/books#mini_flyer

This route matches to /app/controllers/marketing/books_controller.rb, when I actually want it to go to /app/controllers/books/marketing_controller.rb. Is that possible?

-- EDIT --

I can also go this route (pun intended):

resources :books do
  resource :marketing, to: "books/marketing" do
    collection do
      get 'mini_flyer'
    end
  end 
end

Although, I'm not sure if this would be best.

Upvotes: 0

Views: 937

Answers (2)

anusha
anusha

Reputation: 2135

Yes follow your edit routes with small change

resources :books do
  resources :marketing do
    collection do
      get :mini_flyer
      get 'larde_flyer'
    end
  end 
end

It will work and i think it will be the best one

Upvotes: 1

Marian Theisen
Marian Theisen

Reputation: 6354

why don't you build a nested Marketing resource, with a controller and a model (remember, a model doesnt have to be related to an AR table, could be a simple ruby class), like you did with Page. The id for this resource would then by larde_flyer, mini_flyer etc, which you could verify via a whitelist in your controller (eg. with a before_filter).

Upvotes: 1

Related Questions