开发者

How to route to different actions depending on the request method in Rails?

As we all know, a simple

resources :meetings

will generate 7 actions for me. Two of these are index and create. A really cool thing about these two!: The URL for both is /meetings, but when I GET /meetings I am routed to the def index action and when I POST /meetings, I am routed 开发者_如何学JAVAto the def create action. Nice.

Now I want to do this:

resources :meetings do
  member do
    get  'scores'
    post 'scores'
  end
end

And, you guessed it!, I want them to route to different actions in MeetingsController: GETting /meetings/1/scores will route to def scores and POSTing to meetings/1/scores will route to def create_scores.


Try:

resources :meetings do
  member do
    get  'scores' => :scores
    post 'scores' => :create_scores
  end
end

I suppose you will be also interested in having named routes:

resources :meetings do
  member do
    get  'scores' => :scores, :as => 'scores_of'
    post 'scores' => :create_scores, :as => 'create_scores_of'
  end
end

Then you get scores_of_meeting_path and create_scores_of_meeting_path helpers.

Above may be DRYed more with:

get :scores, :as => 'scores_of'


Define the routes such as this:

resources :meetings do
  member do
    get 'scores', :action => "scores"
    post 'scores', :action => "post_scores"
  end
end

But it sounds to me like it would be much easier to create another controller to handle this, as scores to me feels like another resource entirely, even if they don't have their own model association.


Ha! Never underestimate the ability of asking a question well to lead you to its answer.

resources :meetings do
  member do
    get  'scores', :to => "meetings#scores"
    post 'scores', :to => "meetings#create_scores"
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜