url_view/controller 이외에 for (@hogeable) 를 사용할 때

4555 단어 Rails
url_포(다중모드의 실례)를 하고 싶을 때 좀 빠져서 혼자 써도 괜찮을 것 같아요.
전제로 삼다
4
  • view/controller 이외의 URL나는 for를 쓰고 싶다.
    4
  • 그러나, 4Routing잠깐만요.그런 거 싫어
  • 잠깐만요.2점이 포인트다.
    [1] pry(main)> Rails.application.routes.url_helpers.url_for(like.likeable)
    
    ActionController::UrlGenerationError: No route matches ・・・(以下略
    
    😨

    url_for의 정의


    Url Helper 앞에서 Routing UrlFor 같은 모듈을 읽고 있는데 거기서
    actionview/lib/action_view/routing_url_for.rb에서 발췌하다
    method = _generate_paths_by_default ? :path : :url
    builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method)
    
    case options
    when Symbol
      builder.handle_string_call(self, options)
    when Class
      builder.handle_class_call(self, options)
    else
      builder.handle_model_call(self, options)
    end
    
    이렇게 정의된

    HelperMethod Builder를 사용해 보세요.


    3이놈안에서 많이 노력했어, 응.(제대로 읽지 못했다).
    그러므로
    def path_for(hogeable)
      builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(:path)
      builder.handle_model_call(Rails.application.routes.url_helpers, hogeable)
    end
    
    def url_for(hogeable)
      builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(:url)
      builder.handle_model_call(Rails.application.routes.url_helpers, hogeable)
    end
    
    이렇게 정의를 내리면...
    [1] pry(main)> path_for(like.likeable)
    => "/blogs/1"
    
    キタ——————(゜∀゜)——————!!
    라는 뜻이다.

    최후


    확실하다for라고 할 수 있어요.
    근데 아마 원래는 이렇게 안 써도 될 것 같은데, 이게 라일스의 생각이겠죠

    좋은 웹페이지 즐겨찾기