2011-02-11 8 views
2

추가 경로 요소 (슬러그)를 레일스 3의 URL로 전달할 수 있도록 경로를 설정하는 올바른 방법은 무엇입니까? 마법으로 당신은 자원으로 객체를 나열 할 때 쇼와 새롭습니다. 레일 격려,
http://somewebserver.com/topics/1/learning-rails
하지만 /는 경로 구분 간주되기 때문에 나는 아직도이 같은
http://somewebserver.com/topics/1
이러한
http://somewebserver.com/topics/new
http://somewebserver.com/topics/1/edit레일 3 경로 - 슬러그를 허용

+0

URL 스텁의 PARAMS 해시 TopicsController#new에 파견 될 것이다. 현학적 인 태도를 보이려하지 않고 사람들이 올바르게 질문하는 것을 이해하는 데 도움이 될 수도 있습니다. –

답변

0

을 작업 할 것 : 여기

은 예입니다 더 중립적 인 -을 사용하여 slug에서 ID를 분리하십시오.

this screencast을 참조하십시오.

그렇지 않으면 사용자 정의 :id 검증을 통과해야하고 :id/이 포함될 수 있음을 레일스에 알리십시오. 그러나 그렇게 간단하지는 않습니다.

# lib/topic_slugger.rb 
class TopicSlugger 
    AD_KEY = "action_dispatch.request.path_parameters" 

    def self.call(env) 
    controller = (env["PATH_INFO"].split("/")[1].camelize+"Controller").constantize 
    glob = env[AD_KEY][:glob] 
    slug, action_name = nil 
    if glob 
     path_params = glob.split("/") 
     if path_params.length == 1 
     if ["new","edit"].include?(path_params.first) 
      # no slug present 
      action_name = path_params.first 
     else 
      slug = path_params.first 
     end 
     else 
     action_name = path_params.first 
     slug = path_params.last 
     end 
    end 
    env[AD_KEY][:slug] = slug if slug 
    action = if action_name # "new" or "edit" 
       action_name.to_sym 
      else 
       case env["REQUEST_METHOD"] 
       when "PUT" then :update 
       when "DELETE" then :destroy 
       else :show 
       end 
      end 
    controller.action(action).call(env) 
    end 
end 

# config/routes.rb 
require 'topic_slugger' 

Ztest::Application.routes.draw do 
    # handle show, new, edit, update, destroy 
    match 'topics/:id/*glob' => TopicSlugger 
    # handle index, create 
    resources :topics 
end 

이의 요청을합니다 : 당신이 뭔가를 할 수 있도록

1

그것은 당신의 굼벵이는 "1 학습 레일"처럼 보이게 아마 더 나은이지만, 레일 3 이후 지금 allows the use of Rack applications는 경로를 처리하는 형태가 "/topics/1/foo/bar"이고 TopicSlugger Rack 앱에 전달합니다. glob에 조합 액션/슬러그 (예 : "new/learning-rails") 또는 슬러그 ("learning-rails")가 포함되어 있는지 여부를 결정하고 환경 변수의 요청 매개 변수에 슬러그를 추가 한 다음 컨트롤러 동작 자체는 랙 응용 프로그램입니다. "index"및 "create"는 resources 문에 의해 정상적으로 처리됩니다.

그래서 예를 "GET /topics/1/new/learning-rails"을 위해 더 일반적으로 레일 커뮤니티의 URL 슬러그라고 { :id => "1", :slug => "learning-rails, :glob => "new/learning-rails" }