【问题标题】:Call method after submitting form Rails提交表单 Rails 后调用方法
【发布时间】:2013-09-08 23:22:29
【问题描述】:

我有以下型号:

class Coupon < ActiveRecord::Base
  belongs_to :company

  validates :description, presence: true, length: { maximum: 50 }, uniqueness: { case_sensitive: false }
  validates :fine_print, presence: true
end

以及优惠券控制器中的以下方法:

def redeem
  if params[:pin] == @coupon.company.pin
    redirect_to root_path
  else
    flash.now[:notice] = "Incorrect Pin"
    render :show
  end
end

这个表单在a视图中:

<%= form_for( @coupon, :url => coupons_redeem_path( @coupon ), :html => { :method => :post } ) do |f| %>
  <%= label_tag("pin", "Search for:") %>
  <%= text_field_tag("pin") %>
  <%= f.submit "Close Message" %>
<% end %>

我希望表单在点击提交时调用优惠券控制器中的兑换方法,但出现此错误:

没有路线匹配 [POST] "/coupons/redeem.1"

编辑

这些是我的路线:

resources :companies do 
  resources :coupons
end
get 'coupons/redeem'

【问题讨论】:

  • 您不能使用 POST 创建您已经知道 ID 的资源。如果你想使用 POST,你将不得不使用:url =&gt; coupons_redeem_path。您能否将您的路线包含在优惠券资源中?
  • 路线已添加

标签: forms controller ruby-on-rails-4


【解决方案1】:

在您的路由中,couponscompanies 的嵌套资源。因此,您应该选择以下备选方案之一:

第一个:

resources :companies do 
  resources :coupons do
    post :redeem, on: :member
  end
end

这会导致这样的助手:redeem_company_coupon_path(company, coupon)(并通过 POST 发送 smth)。

如果您不想将公司包括在您的路径中,您可以选择第二个:

resources :companies do 
  resources :coupons
end   
post 'coupons/:id/redeem', to: 'coupons#redeem', as: :redeem_coupon

之后你可以使用redeem_coupon_path(coupon) helper

【讨论】: