Rails 路由优先级优先

Rails Routing Precedence favors the first

所以我一直致力于 rails 项目,该项目在同一个控制器中定义了两个不同的创建操作。 这是我的控制器:

class SmsSendsController < ApplicationController
  def new
    @at = SmsSend.new
    @contact = Contact.find_by(id: params[:id])
  end
  def create
    @at = SmsSend.create(sms_params)
    if @at.save!
    @con = current_user.contacts.find_by(id: @at.contact_id)
    AfricasTalkingGateway.new("trial-error").sendMessage(@con.phonenumber, @at.message)
    end
  end
  def new_all
    @at = SmsSend.new
    @contact = Contact.find_by(id: params[:id])
  end
  def create_all
    @at = SmsSend.create(sms_params)
    if @at.save!
    current_user.contacts.each do |c|
      AfricasTalkingGateway.new("trial-error").sendMessage(c.phonenumber, @at.message)
    end
    end
 end

  private
  def sms_params
    params.require(:sms_send).permit(:mobile, :message, :contact_id)
  end
end

在我的

routes.rb

文件,我使用了自定义路由和足智多谋的路由来定义第一个和第二个 new/create 操作的路由:

Rails.application.routes.draw do
  devise_for :users
  get 'sms_sends/new_all', to: 'sms_sends#new_all'
  post 'sms_sends', to: 'sms_sends#create_all'
  resources :contacts
  resources :sms_sends
  root 'contacts#index'
end

因此,当且仅当其路线位于另一个之前时,这两个 post 动作才会起作用。有什么办法可以摆脱优先级吗?或者我哪里出错了?

谢谢。

So both post actions will work if and only if its routes are placed before the other.

这就是您应该如何定义路由的工作方式。因为在 routes.rb 中定义的路由将从 top-to-bottom 编译。因此,如果您的 自定义路由 前面有 资源丰富的路由 ,那么自定义路由 将与您足智多谋的路线发生冲突

Is there a way I can get rid of the precedence?

像这样将它们定义为集合路线

resources :sms_sends do
  get 'sms_sends/new_all', to: 'sms_sends#new_all', on: :collection
  post 'sms_sends', to: 'sms_sends#create_all', on: :collection
end

以上将生成带有路径助手的路由,如下所示

sms_sends_new_all_sms_sends   GET    /sms_sends/sms_sends/new_all(.:format)   sms_sends#new_all
sms_sends_sms_sends           POST   /sms_sends/sms_sends(.:format)           sms_sends#create_all

为了更好的可读性,您可以像这样更改您的自定义路由

resources :sms_sends do
  get 'new_all', to: 'sms_sends#new_all', on: :collection
  post 'create_all', to: 'sms_sends#create_all', on: :collection
end

这将生成如下所示的路径助手

new_all_sms_sends             GET    /sms_sends/new_all(.:format)      sms_sends#new_all
create_all_sms_sends          POST   /sms_sends/create_all(.:format)   sms_sends#create_all