MrBliz
MrBliz

Reputation: 5908

How can i create the following route

Rails beginner, so please don't bite. I've taken over the maintenance/development of a rails an app, but still learning the ropes

I'd like to generate the following route :

/events/1/Project/2/Pledge

Where 1 is the eventId and 2 is the Project Id.

I have a project controller and and events controller. The pledge action is on the Project controller

EDIT: In answer to @wacko's comment below.

a)Ignore the casing and pluralization of the url i asked for (I realise that invalidates the original question somewhat...)

An event has multiple projects, The pledge action will take the user to a page where they can enter multiple pledges for a particular project.

Perhaps instead the Pledge action should be on the Events Controller instead?

and the URL something like 'events/1/pledge/2' (Where 2 is the projectId)

Upvotes: 0

Views: 55

Answers (5)

HarsHarI
HarsHarI

Reputation: 911

jsut use this way

resources :events do
 resource :projects do
   get '/pledge'
 end
end

Upvotes: 1

Achrome
Achrome

Reputation: 7821

What you are looking for is called a nested resource, that is to say that there is a parent child relationship between two resources.

resource :events do
  resource :projects do
    get :pledge, :on => :member
  end
end

For this to work, your models would look something like this

class Event < ActiveRecord::Base
  has_many :projects
end

And

class Project < ActiveRecord::Base
  belongs_to :event
end

Upvotes: 2

Santhosh
Santhosh

Reputation: 29144

resources :events do
  resources :projects do
    member do
      get :pledge
    end
  end
end

You can change get to the http method you want. You can use collections if you need a route like /events/1/projects/pledge

collection do
  get :pledge
end

run rake routes from the project root folder to see a list of routes generated

Upvotes: 1

toolz
toolz

Reputation: 891

resources :events do
  resource :projects do
    resources :pledge
  end
end

this will give you the ability to set the scope in your controllers and have access to all 7 REST verbs

Upvotes: 1

Slicedpan
Slicedpan

Reputation: 5015

The following should work

get '/events/:event_id/projects/:id/pledge' => 'projects#pledge'

In your controller action you can get the event_id and project_id from the params hash as params[:event_id] and params[:id] respectively

Upvotes: 1

Related Questions