2010-11-26 76 views
3

我有一个类似多态的关联(不是真正的Rails)关于一个可评论的实现。尽管如此,我希望能够对所有评论使用相同的视图。对于我的命名路线,我只想打电话给edit_comment_path,并让它进入我的新方法。Rails 3重写命名路由

我的路线将是这个样子:

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 

回答

3

其实,这些都不是必要的,内置polymorphic_url方法效果很好:

@commentable被设定在一个在的before_filter CommentsController

<%= 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']) %> 

EDIT

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 
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 
+0

我认为包装方法是最好的,因为它使事情更具可读性。快速提问。我有自己的方法build_named_route_path(klass),它可以像[:main,@commentable,@object]一样使用数组。有更简单的方法来解析这个使用ActiveSupport? – Dex 2010-11-27 04:19:59

+0

另外,您发布的方法不起作用。矿井适用于除索引视图外的所有视图。很奇怪。 – Dex 2010-11-27 05:25:34