如何在Rails中覆盖自动生成的URL?

时间:2015-05-19 19:41:20

标签: ruby-on-rails ruby-on-rails-4

是否可以覆盖Rails自动生成的URL?例如,假设您有一个对Photo和Post具有多态性的注释对象。假设我们希望以不同的方式处理每个父级的注释对象,因此我们有两个控制器:

resources :photo, shallow: true do
  resources :comments, controller: :photo_comments
#...
resources :post, shallow: true do
  resources :comments, controller: :post_comments
end

现在我想这样做:

# A Photo comment
= link_to "Open", comment # => /photo_comment/1

# A Post comment
= link_to "Open", comment # => /post_comment/2

这可能吗?或者我是否必须限定整个路径,即link_to "Show", photo_comment_path(comment)

我不想使用嵌套路线。

2 个答案:

答案 0 :(得分:1)

有问题的网址由polymorphic_url生成。我看待它的方式,你真的不需要覆盖它,只需传递父母和评论,如下所示:

link_to "Open", [:whatever_namespace_there_is, comment.parent, comment]

这比通过辅助方法指定路径更灵活,省去了手动检查父类型的麻烦。

答案 1 :(得分:0)

哦,要回答您的问题,您可以覆盖/复制gems/actionview-<ver>/lib/action_view/helpers/url_helper../helpers/tag_helper中的方法,具体取决于您的操作方式。然后你将在config/initializers中创建一个.rb文件。这是一个如何工作的例子

ActionView::Helpers::UrlHelper.module_eval do
  def link_to_comment(comment_controller, name = nil, options = nil, html_options = nil, &block) 
    #create new method based on original, add new controller argument
    html_options, options, name = options, name, block if block_given?
    options ||= {}

    html_options = convert_options_to_data_attributes(options, html_options)

    url = url_for(options)
    urla = url.split("/")#let it generate the url
    url = ""
    urla.each do |part|
      unless part == "comments"#go through each part and find the comments section
        url<<part
        url<<"/"
      else
        url<<comment_controller#put the controller where it needs to be
        url<<"_"
        url<<part
        url<<"/"
      end
    end
     html_options['href'] ||= url

    content_tag(:a, name || url, html_options, &block)
  end
end

您可以在需要时调用此方法,<%= link_to_comment("post", "View", comment) %>

重新启动服务器,应该实现它。如果您的两条评论资源都使用您需要定义的相同路径(例如/post_comment/,并且您不需要/comment/而非resources :comments, controller: :photo_comments, path: '/photo_comments'做任何方法覆盖。

相关问题