0

这里的总新手^^所以我的页脚中有一堆静态页面,我想为其创建一条路线。现在,我正在使用 get 来创建这样的路线:

Rails.application.routes.draw do
  root 'static_pages#home_page'
  get 'static_pages/secret'

  get 'static_pages/stripe_button'
  get 'about_us', to: 'static_pages#about_us'
  get 'rules', to: 'static_pages#rules'
  get 'faq', to: 'static_pages#faq'
  get 'community', to: 'static_pages#community'
  get 'terms', to: 'static_pages#terms'
  get 'privacy', to: 'static_pages#privacy'
end

理想情况下,我试图将所有这些浓缩成这样的资源:

resources :static_pages, only: [:index] do
  get :terms, :community, :privacy, :rules, :faq, :about_us, :stripe_button, :secret
end

这是页面的页脚 li:

<div class="col">
  <ul>
    <li><%= link_to "About Us", 'about_us', class: 'nav-link d-inline-block' %></li>
    <li><%= link_to "Rules", 'rules', class: 'nav-link d-inline-block' %></li>
    <li><%= link_to "FAQ", 'faq', class: 'nav-link d-inline-block' %></li>
  </ul>
</div>
<div class="col">
  <ul>
    <li><%= link_to "Community", 'community', class: 'nav-link d-inline-block' %></li>
    <li><%= link_to "Terms", 'terms', class: 'nav-link d-inline-block' %></li>
    <li><%= link_to "Privacy", 'privacy', class: 'nav-link d-inline-block' %></li>
  </ul>
</div>

如何摆脱所有获取并将所有获取浓缩为一个资源?

红宝石 2.7.1 轨道 6.1.3

多谢 :)

4

2 回答 2

0

First of all, resources is a concept that revoles around an actual resource, or record if you will. Your static routes don't really follow that, so you the way you did it is actually the right way to do it (see also here: https://guides.rubyonrails.org/routing.html#non-resourceful-routes).

If your sole purpose is refactoring your routes file, I wouldn't worry too much, in fact I would leave it as is because I think it's more important to follow the concepts.

If you still want to go ahead and you don't care too much what the actual urls look like you can do it like so:

resources :static_pages, only: [:index] do
    collection do
      get :terms, :community, :privacy, :rules, :faq, :about_us, :stripe_button, :secret
    end
  end

Urls will look like this then /static_pages/terms.

The collection makes sure there is no :id needed in the routes. You can always double check in the terminal with rails routes - also in order to find the prefix for the link_to helper (will be terms_static_pages_path).

于 2021-03-18T17:09:38.467 回答
0

您可能会在那里找到想法 Rails routing: resources with only custom actions

这可能是您的解决方案:

scope '/', controller: :static_pages do
    get :terms, :community, :privacy, :rules, :faq, :about_us, :stripe_button, :secret
end

如果您不想手动键入所有操作,则可以使用类方法.action_methods并从中排除您需要特定路线的所有操作:

scope '/', controller: :static_pages do
  (StaticPagesController.action_methods.to_a - ["home_page", "secret"])
    .each do |action_method|
      get action_method
    end
end 
于 2021-03-18T17:29:09.310 回答