"orders-6ren">
gpt4 book ai didi

ruby-on-rails - Rails 路由变量

转载 作者:数据小太阳 更新时间:2023-10-29 08:25:10 25 4
gpt4 key购买 nike

订单可以有多种状态。我想为那些创建命名路由。我需要将状态作为参数传递给 Controller ​​。这是我的想法,但显然行不通。

match "order/:state/:id" => "orders#%{state}", as: "%{state}"

所以我希望 order/address/17 路由到 orders#address,其中 :state 和 :id 作为参数传入。同样,order/shipping/17 会路由到 orders#shipping,同样会传入 :state 和 :id。

这是 Controller 。

class OrdersController < ApplicationController

before_filter :load_order, only: [:address, :shipping, :confirmation, :receipt]
before_filter :validate_state, only: [:address, :shipping, :confirmation, :receipt]


def address
@order.build_billing_address unless @order.billing_address
@order.build_shipping_address unless @order.shipping_address
end


def shipping
@shipping_rates = @order.calculate_shipping_rates
end


def confirmation

end


def receipt

end

private

def load_order
@order = Order.find(params[:id])
end

# Check to see if the user is on the correct action
def validate_state
if params[:state]
unless params[:state] == @order.state
redirect_to eval("#{@order.state}_path(:#{@order.state},#{@order.id})")
return
end
end
end

end

这是我们最终的结果:

routes.rb

%w(address shipping confirmation receipt).each do |state|
match "order/#{state}/:id", :to => "orders##{state}", :as => state, :state => state
end

orders_controller.rb

def validate_state
if params[:state]
unless params[:state] == @order.state
redirect_to(eval("#{@order.state}_path(@order)"))
return
end
end
end

最佳答案

您将无法使用那种语法创建动态命名路由,但您基本上只是使用 :state 作为 :action。如果将 :state 替换为 :action 并手动指定 Controller ,它将起作用。显然,您必须更改代码以查看 params[:action] 而不是 params[:state](或将该变量映射到 before_filter 中),但除此之外它应该可以正常工作。

match "order/:action/:id", :controller => "orders"

请注意,如果订单具有 RESTful 资源映射,如 createdelete,此路由将允许对它们发出 GET 请求,这很糟糕;您可能只想为要完成的每个操作添加显式路由。这将让您获得 params[:state],以及:

%w(address shipping).each do |state|
match "order/#{state}/:id", :to => "orders##{state}", :as => state, :state => state
end

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

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