gpt4 book ai didi

ruby-on-rails - Rails 路由优先级优先

转载 作者:行者123 更新时间:2023-12-04 15:54:21 27 4
gpt4 key购买 nike

因此,我一直致力于一个 Rails 项目,该项目在同一个 Controller 中定义了两个不同的创建操作。 这是我的 Controller :

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

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

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 Action 才会起作用。有什么办法可以摆脱优先级吗?或者我哪里出错了?

谢谢。

最佳答案

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

关于ruby-on-rails - Rails 路由优先级优先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52455967/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com