我有一个类似多态的关联(不是真正的 Rails 关联)用于 Commentable 实现。不过,我希望能够对所有评论使用相同的 View 。对于我的命名路由,我只想调用 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
最佳答案
实际上,这些都不是必需的,内置的 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
关于ruby-on-rails - Rails 3 重写命名路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4286543/