【问题标题】:No matching Route error in Ruby on RailsRuby on Rails 中没有匹配的路由错误
【发布时间】:2017-09-11 12:23:06
【问题描述】:

我是 Ruby on Rails 的新手。我已经尝试了两天为控制器中的方法定义路由,但错误显示“没有路由匹配 [GET]”。 这是代码

donations Controller:

before_action :set_donation, only: [:show, :edit, :update, :destroy, :create_user_account]
  before_action :set_campaign, only: [:new, :create_user_account]
//this is the method that i want to call 
  def create_user_account
  end

这是我的路线文件

Rails.application.routes.draw do
  resources :donations, except: [:new, :create]
 get 'donations/create_user_account' => 'donations#create_user_account'
  resources :campaigns do
    resources :donations, only: [:new, :create, :create_user_account]
    get 'donations/create_user_account' => 'donations#create_user_account'
  end
  resources :organizations

  devise_for :users

  root to: "campaigns#latest"
end

路线显示我的路线名称,但是当我点击路线时出现“不匹配”路线错误。

路线1: campaign_donations_create_user_account_path GET /campaigns/:campaign_id/donations/create_user_account(.:format) 捐款#create_user_account 路线2:

donations_create_user_account_path  GET /donations/create_user_account(.:format)    
donations#create_user_account

我想呼叫路线 2,但没有路线可用

我这样称呼我的路线 2

http://localhost:3000/donations/create_uer_account

这是错误

【问题讨论】:

  • 你做错了,你应该阅读路线类型。 stackoverflow.com/questions/3028653/… 或发送 ID 作为 url 中的查询参数。
  • 您附加了一个与错字 create_uer_account 相关的错误 ...
  • @jenvvv 已编辑但同样的错误根本不是问题。

标签: ruby-on-rails routing


【解决方案1】:

错误是因为这一行

resources :donations, except: [:new, :create]

routes.rb 中在其他人之前。 Rails 与它在 routes.rb 文件中找到的第一条路线相匹配。

它应该看起来像这样

get 'donations/create_user_account' => 'donations#create_user_account'
resources :donations, except: [:new, :create]

然后 Rails 首先匹配你的create_user_account

【讨论】:

  • 根据您的建议更改代码后,错误显示 ActiveRecord::RecordNotFound in DonationsController#create_user_account Couldn't find Donation with 'id'= def set_donation "@donation = Donation.find(params[ :id])" end 为什么总是在 set_donation 方法里面???
  • 因为你在before_action中声明了它
  • 还是同样的错误,我的代码是 before_action :set_donation,只有:[:create_user_account, :show, :edit, :update, :destroy]
  • 它用那个before_action调用set_donation,从before_action中删除create_user_account
  • 非常感谢您的帮助。以后我也会打扰你的。 :)
猜你喜欢
  • 2016-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多