Rails POST 把参数 id 当成 format

autumnwolf · 2014年04月09日 · 最后由 autumnwolf 回复于 2014年04月09日 · 2832 次阅读

view:

<%= button_to t('home.add_to_cart'), line_items_path(product)%>

这样点击按钮的时候直接 http://localhost:3000/line_items.4 把 product 的 id 变成了 format.

求原因! PS:

 Prefix Verb                 URI Pattern                               Controller#Action
line_items GET           /line_items(.:format)                  line_items#index
           POST              /line_items(.:format)                   line_items#create
new_line_item GET    /line_items/new(.:format)           line_items#new
edit_line_item GET     /line_items/:id/edit(.:format)      line_items#edit
line_item GET             /line_items/:id(.:format)             line_items#show

Log:

 params {\"authenticity_token\"=>\"6q3Btd5+k83cNUOjW75NRLQFa5daONl/gb14xpMB5Fs=\", \"action\"=>\"create\", \"controller\"=>\"line_items\", \"format\"=>\"4\"}"
Completed 406 Not Acceptable in 69ms

ActionController::UnknownFormat (ActionController::UnknownFormat):
  app/controllers/line_items_controller.rb:9:in `create'

应该是line_item_path吧,注意没有复数

#1 楼 @Martin91

 Prefix Verb                 URI Pattern                                     Controller#Action
line_items GET           /line_items(.:format)                        line_items#index
           POST              /line_items(.:format)                         line_items#create
new_line_item GET    /line_items/new(.:format)                 line_items#new
edit_line_item GET     /line_items/:id/edit(.:format)            line_items#edit
line_item GET             /line_items/:id(.:format)                   line_items#show

Routes 是这样的 我要调用的是 create 方法,POST 那个,应该是 line_items_path 吧?如果是 line_item_path 不就是 show 那个方法了么?

:method => :post

#3 楼 @miclle button_to 默认就是 post

#4 楼 @autumnwolf 哦,我以为跟 link_to 一样 仔细看你的问题,你是不是想创建一个属于 product 的 line_item 呢?如果是的,那应该写嵌套路由

#5 楼 @miclle 我虽然是创建属于 product 的 line_item,但是我不需要

/products/line_item/id

这样为什么要嵌套路由呢?

单层 RESTful 路由的 index, create, new 是不需要路径参数的,所以你提供的参数变成了 format。

如果直接拿 product 做参数,你需要product/123/line_items这样的路由

resources :products do
  resources :line_times
end

嵌套路由在这里是非常合适的。

如果你实在不喜欢嵌套的,而喜欢直接line_items。那你需要在发送 POST 参数时手动提供 product_id,不然 controller 没法知道这个 line_item 属于谁。这样会麻烦一些。

/line_items/:id

#7 楼 @billy 之前以为 has_many,belongs_to 就可以了呢,谢谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号