2010-11-26 15 views
3

私は、Commentable実装のために多相のような関連付けをしています(本当の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 

EDIT

# 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は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 
でbefore_filterに設定されています
+0

あなた自身の質問に答えるときに、この回答に正しい/合格とマークすることを忘れないでください。 – Jeremy

+0

こんにちは、ありがとう。私はその大渦巻きにも近づいていた。私はRailsのドキュメントでこれについて多くを見つけることができませんでした - ブログなどに広がっているようです。あなたは '@ commentable'ロジックを共有することができますか?それはかなり面白いです –

+1

@Joseph Weissmanは私の更新を見ます。このようなものはうまくいくはずです。私は古いコードから切り取って貼り付けましたが、質問は古いものです。 – Dex

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

+0

また、投稿したメソッドが機能しません。 Mineは、インデックスビュー以外のすべてのビューで機能します。非常に奇妙な。 – Dex

関連する問題