简体   繁体   中英

In a Rails app, how can I use a button to run a non-restful controller method? Getting no routes error

In my application I have a link_to helper method:

<%= link_to "Downgrade", :controller => :subscriptions, :action => :downgrade, class: "btn btn-primary", remote: true %> 

In my controller I have this code:

class SubscriptionsController < ApplicationController
  respond_to :js

  def downgrade
    # some code
  end
end

I am getting this error:

No route matches {:action=>"downgrade", :class=>"btn btn-primary", :controller=>"devise/subscriptions"}

Here is my routes.rb code:

Rails.application.routes.draw do
 resources :wikis
 devise_for :users
 resources :users, only: [:update]
 root to: 'welcome#index'
 resources :charges, only: [:new, :create]
end

I know Rails is expecting a route for this but I don't know what route I would use since the method isn't a restful verb. Maybe there is another way without using the link_to which allows me to directly call a controller method from a view? Maybe I need to restructure where things are as well. Any help is appreciated.

Let me know if there is more code you would need to fully assess this situation.

Basic setup

first you need to setup your route in routes.rb

get 'downgrade' => 'subscriptions#downgrade', :as => :downgrade_subscription

This will redirect /downgrade to your subscriptions controller & downgrade action. The as option saves this route into a variable you can call from all your views .

<%= link_to "Downgrade", downgrade_subscriptions_path, class: "btn btn-primary", remote: true %>

Further configuration

You can also nest this route inside your subscription resources like so:

resources :subscriptions do
  get 'downgrade' => 'subscriptions#downgrade', :as => :downgrade_subscription
end

This will create the path /subscriptions/downgrade instead of /downgrade .

The Rails Docs on routing does a great job explaining this in more detail. Definitely check it out!

或者你可以在你的routes.rb上尝试

match '/downgrade_subscription', :to => 'subscriptioni#downgrade', :via => :get

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