Rails路由,不能在嵌套资源上使用#create动作

时间:2018-04-18 15:24:43

标签: ruby-on-rails forms routes

我有用户付款的路线

配置/ routes.rb中

  resources  :users do
resources :payment_sources, only: [:index, :new, :create, :destroy], controller: 'users/payment_sources'
end

正在运行rake routes | grep payment_source给我这个:

        user_payment_sources GET      /users/:user_id/payment_sources(.:format)      users/payment_sources#index
                             POST     /users/:user_id/payment_sources(.:format)      users/payment_sources#create
     new_user_payment_source GET      /users/:user_id/payment_sources/new(.:format)  users/payment_sources#new
         user_payment_source DELETE   /users/:user_id/payment_sources/:id(.:format)  users/payment_sources#destroy

所以我没有路径或网址助手......所以我以自己的形式继续编写了网址

应用程序/视图/用户/ payment_sources / new.html.erb

<%= form_with(url: 'users/payment_sources#create' , id: "payment-form") do |form| %>

这让我回到了错误

No route matches [POST] "/users/16/payment_sources/users/payment_sources"

显然我做错了什么,但我不知道是什么。关于这种嵌套资源的建议吗?

我的控制器代码是:

*应用程序/控制器/用户/ payments_sources_controller.rb **

class Users::PaymentSourcesController < ApplicationController

def new
end

def create
token = params[:stripeToken]

customer = Stripe::Customer.create({
  email: current_user.email,
  source: token,
})

payment = PaymentSource.create(
  user:           current_user,
  card_last4:     params[:card_last4],
  card_exp_month: params[:card_exp_month],
  card_exp_year:  params[:card_exp_year],
  card_brand:     params[:card_brand]
)

redirect_to root_path, notice: "Hurray, your debit card has been saved"
 end
end

如何在PaymentSourcesController上访问我的创建操作?

3 个答案:

答案 0 :(得分:2)

尝试以下

<%= form_with(url: "/users/#{current_user.id}/payment_sources", 
              id: "payment-form", method: post) do |form| %>

OR

<%= form_with(url: user_payment_sources_path(user_id: current_user), 
              id: "payment-form", method: post) do |form| %>

答案 1 :(得分:1)

如您所见,当您执行rails路由时,create的url是user_payment_source。所以在你的表单中你应该像这样替换url <%= form_with(url: 'user_payment_sources_path' , id: "payment-form", method: "post") do |form| %>

答案 2 :(得分:0)

试试这个:

<%= form_with(url: user_payment_sources_url, id: "payment-form", method: "post") do |form| %>

希望这有帮助:)