如何在Rails中创建自定义的URL助手?

时间:2018-11-21 16:30:30

标签: ruby-on-rails ruby ruby-on-rails-5

我希望可以从控制器,视图,测试中访问此自定义url帮助器,以_url和_path结尾。另外,它还应该可以在最后添加参数作为url帮助器。

def reviews(reviewable)
  "/reviews/#{reviewable.class}/#{reviewable.id}"
end
reviews_url Book.find(1) # /reviews/Book/1
reviews_path Film.find(3) # /reviews/Film/3

Review.reviewable是多态的。

配置/路由

get "reviews/:reviewable_type/:reviewable_id" => "reviews#index"

2 个答案:

答案 0 :(得分:2)

我只将路线定义为:

resources :books do
  resources :reviews, only: [:new, :create, :index]
end

resources :films do
  resources :reviews, only: [:new, :create, :index]
end

这将创建以下路线:

books/:book_id/reviews
films/:film_id/reviews

这是定义nested resources的常规RESTful方法。而且更重要的是,它可以与Rails polymorphic route helpers一起使用。

如果需要,可以使用路由问题将其干燥。

concern :reviewable do
  resources :reviews, only: [:new, :create, :index]
end

resources :books, concerns: :reviewable
resources :films, concerns: :reviewable

它为您提供了命名的路由助手book_reviews_path(@book)film_reviews_path(@film)。您还可以使用多态路由助手:

<%= link_to "Reviews for #{@reviewable.title}" [@reviewable, :reviews] %>
...
<%= form_for([@reviewable, @reviewable.review.new]) do %>
...
redirect_to [@reviewable, :reviews], notice: 'Review created'

答案 1 :(得分:0)

即使我的问题已经很久以前回答了,我还是要根据问题的标题添加另一个答案。 因此,如果您实际上想创建自定义的url和路径帮助器,那么以下是示例的答案:Generating a full resourceful path giving only the last resource to the routes helper

Rails文档:https://api.rubyonrails.org/classes/ActionDispatch/Routing/Mapper/CustomUrls.html#method-i-direct