代码之家  ›  专栏  ›  技术社区  ›  Dex

Rails 3重写命名路由

  •  3
  • Dex  · 技术社区  · 14 年前

    对于可注释的实现,我有一个类似多态的关联(不是真正的Rails关联)。不过,我希望能够对所有评论使用相同的视图。对于我指定的路线,我只想打电话给 edit_comment_path 去我的新方法。

    我的路线会是这样的:

    resources :posts do
      resources :comments
    end
    
    resources :pictures do
      resources :comments
    end
    
    resources :comments
    

    现在我已经超越了 编辑注释路径 在helper模块中,但是 resources :comments 一直有人打电话来。我在保存 资源:注释 因为我希望能够直接访问评论和我依赖的一些混合。

    这是我的重写方法 module CommentsHelper :

      def edit_comment_path(klass = nil)
        klass = @commentable if klass.nil?
        if klass.nil?
          super
        else
          _method = "edit_#{build_named_route_path(klass)}_comment_path".to_sym
          send _method
        end
    

    编辑

    # take something like [:main_site, @commentable, @whatever] and convert it to "main_site_coupon_whatever"
      def build_named_route_path(args)
        args = [args] if not args.is_a?(Array)
        path = []
        args.each do |arg|
          if arg.is_a?(Symbol)
            path << arg.to_s 
          else
            path << arg.class.name.underscore
          end
        end
        path.join("_")
      end
    
    2 回复  |  直到 14 年前
        1
  •  3
  •   Dex    13 年前

    实际上,这些都不是必需的,内置的多态url方法工作得很好:

    @commentable在CommentsController中的before_过滤器中设置

    <%= link_to 'New', new_polymorphic_path([@commentable, Comment.new]) %>
    
    <%= link_to 'Edit', edit_polymorphic_url([@commentable, @comment]) %>
    
    <%= link_to 'Show', polymorphic_path([@commentable, @comment]) %>
    
    <%= link_to 'Back', polymorphic_url([@commentable, 'comments']) %>
    

    编辑

    class Comment < ActiveRecord::Base
       belongs_to :user
       belongs_to :commentable, :polymorphic => true
    
       validates :body, :presence => true 
    end
    
    
    
    class CommentsController < BaseController
    
      before_filter :find_commentable
    
    private 
    
      def find_commentable
        params.each do |name, value|
          if name =~ /(.+)_id$/
            @commentable = $1.classify.constantize.find(value)
            return @commentable
          end
        end
        nil
      end
    
    end
    
        2
  •  0
  •   tadman    14 年前

    您可能在尝试使用辅助模块跨越骑行路线时遇到问题。尝试在应用程序控制器中定义它并使其成为 helper_method 也。您还可以调整名称以避免冲突,并将其用作包装器,如下所示:

    helper_method :polymorphic_edit_comment_path
    def polymorphic_edit_comment_path(object = nil)
      object ||= @commentable
      if (object)
        send(:"edit_#{object.to_param.underscore}_comment_path")
      else
        edit_comment_path
      end
    end