Rails 3 Overriding Named Routes

I have a polymorphic-like association (and not a true Rails-one) to implement Commentable. However, I would like to use the same views for all comments. For my named routes, I just want to call edit_comment_pathand go to my new method.

My routes will look something like this:

resources :posts do
  resources :comments
end

resources :pictures do
  resources :comments
end

resources :comments

I am currently overridden edit_comment_pathin a helper module, but the one that is generated resources :commentscontinues to receive the call. I save resources :commentsbecause I would like to have access to comments directly, and some of them rely on him.

Here is my override method in 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
2

, , 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
+3

. 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

Source: https://habr.com/ru/post/1777085/


All Articles