简体   繁体   中英

How can i route a mothod for more than one controller rails 6

i have this in my routes.rb

  get "invoices/log_out" => "users#logout", :as => "log_out"

this seems to work only in localhost:3000/invoices/new/log_out as when i am at localhost:3000/invoices and i click on log out i have the following error

No route matches [GET] "/log_out"

so i want to make it work in all my controllers were are five something like get "all_controllers/log_out" => "users#logout", :as => "log_out"

   <nav class="navi_me">
          <ul>
          <li><a href="/proms/add_prom">Εισαγωγη Προμηθευτη</a></li>
          <li><a href="/proms">Προμηθευτες</a></li>
          <li><a href='/items'>Προϊόντα</a></li>
          <li><a href='/items/insert'>Εισαγωγη Προϊόν</a></li>
          <li><a href='/invoices'>Τιμολόγια</a><li> 
          <li><a href='/invoices/new'>Εισαγωγη Τιμολόγιου</a><li>
          <li><a href='/pbinvoices'>Πιστωτικά Τιμολόγια</a><li>
          <li><a href='/pbinvoices/new'>Εισαγωγη Πιστωτικου Τιμολόγιου</a><li>
          <li><a href='/census'>Απογραφες</a><li>
          <li><a href='/users/setting'>User Setting</a></li>
          <li><a href="log_out">Αποσύνδεση</a></li>
        </li>
      </ul>
      </nav>
    ```

  def logout
    session[:user_id] = nil
    redirect_to users_login_path , :notice => "Logged out!"
  end 

Looking at your route:

get "invoices/log_out" => "users#logout", :as => "log_out"

When someone hits localhost::3000/invoices/log_out it routes the request to the logout method on your UsersController . Changing the path part to 'all_controllers/log_out' won't change anything about the behaviour of your app other than change the text of the path. It doesn't really matter to your problem, but since logging out is a single global operation, you're probably better off with just '/log_out' as the route path to keep things simple.

You didn't include any snippets of your view code, but your problem is almost certainly in how you're specifying the link_to . The :as => "log_out" part of your route defines an alias for the route. Rails creates URL helpers automatically using that alias ( log_out_path and log_out_url ) that you can use in your views and controllers to link to that operation:

<%= link_to "Logout", log_out_path %>

Using the URL helpers ensures that your code is using right route even if you later change the actual path in routes.rb .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM