Named routes inserting a . instead of a /

旧城冷巷雨未停 提交于 2020-01-05 12:08:24

问题


I've been having trouble with named routes in rails 4 (Named route for non resource nesting).

I've moved onto something else, but still struggling with the same problem of named routes for non resource urls.

This is my route from rake routes:

         GET    /messages/:id/report/:reply_token(.:format)     messages#report
messages POST   /messages(.:format)                             messages#create

and my routes.rb

resources :messages, only: [:create] do
  member do
    get 'report/:reply_token', :action => 'report'#, :as => :message
  end
end

Because of the problem I had in my post linked at the top, I'm trying to get a url to the /messages/:id/report/:reply_token route by doing the following:

"#{messages_url(@message, :host => "localhost:3000")}/report/#{@message.reply_token}"

But it's giving me this:

http://localhost:3000/messages.110/report/6bBw22TdaRYcQ3iVzW1ZwA

Why is there a . between the 'messages' and the '110' (message_id)?

Instead of @message, I've also tried @message.id in the messages_url(). I've also tried this: report_message_path(message_id: @message.id, reply_token: @message.reply_token) but got the same error as in my question linked above. I've also tried message_url() instead but it gives undefined method 'message_url'.


回答1:


You are mixing up routes. messages_url is to generate a URL for create action which does not have ID in its route. Rails assumes 110 is the format and uses the second route (which is named as messages)

messages POST   /messages(.:format) 

As a solution, name your route like this and also add show action

resources :messages, only: [:create,:show] do
  member do
    get 'report/:reply_token', :action => 'report' , :as => :custom_message
  end
end

And,

custom_message_url(@message, :host => "localhost:3000")

More about naming routes here.

Answerd here already - Rails _path helper generating path with format not id



来源:https://stackoverflow.com/questions/22023884/named-routes-inserting-a-instead-of-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!