Rails 3覆盖命名路由

时间:2010-11-26 15:29:13

标签: ruby-on-rails routing

对于Commentable实现,我有类似多态的关联(不是真正的Rails)。我希望能够对所有评论使用相同的视图。对于我的命名路线,我只想打电话给edit_comment_path并让它转到我的新方法。

我的路线看起来像这样:

resources :posts do
  resources :comments
end

resources :pictures do
  resources :comments
end

resources :comments

现在我已经在帮助器模块中覆盖了edit_comment_path,但由resources :comments生成的那个继续被调用。我保留resources :comments,因为我希望能够直接访问评论,并且我依赖它的一些Mixins。

以下是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 个答案:

答案 0 :(得分:3)

实际上,这些都不是必需的,内置的polymorphic_url方法运行得很好:

@commentable在CommentsController

中的before_filter中设置
<%= 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

答案 1 :(得分:0)

您可能无法尝试使用辅助模块覆盖路线。尝试在ApplicationController中定义它并使其成为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
相关问题