Rails 一个 Rails 细节问题——路由的先后顺序不同,结果不同

xautjzd · August 03, 2013 · Last by xautjzd replied at August 04, 2013 · 2323 hits

最近刚开始看 rails,在动手的过程中发现:路由的先后顺序不同,结果便大不相同。

在学习过程中我手动地完成 CRUD 功能时,在写到 config/routes.rb 这块时发现一个怪问题:

get "/posts", to: "posts#index", as: :posts

post "/posts", to: "posts#create"

这样没问题。但将他们换个顺序就不行了。

请问这是什么原因呢?

1 Floor has deleted

顺序优先 另注意 as: :posts

我想说:welcome to the script world.

#2 楼 @xiaogui 缺省情况下就是和前边的名称一样是吧?既然顺序优先,那后一个缺省是啥呢

两种情况下比较下 rake routes | grep post 的结果

路由的定义有先后的,以首次定义为准。。

“as:”是干嘛的?

#7 楼 @Blues 是用于指定生成的 route helper 方法的前缀,比如 LZ 原来的代码会生成posts_path以及posts_url这两个 helper,你也可以根据你的需要改成如:

get "/posts", to: "posts#index", as: :my_posts

这样生成的 helper 则是my_posts_path以及my_posts_url

#6 楼 @small_fish__ 是有先后顺序,但是为啥 post 先不行,而 get 先就可以?

You need to Sign in before reply, if you don't have an account, please Sign up first.