2010-11-26 86 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