简体   繁体   中英

How can I call a “create” action from the link_to helper?

I have seen this question answered here, but unfortunately the answer does not work. FYI this is a Rails 2.3.11 application.

I want to call create with this link_to helper against a RESTful resource:

link_to("Add", part_types_path(myid), :method => :post)

Now very, very strangely, the id that I'm passing in to the URL helper is being interpreted as "format" by the Rails application! So the link comes out to be:

/part_types.12345

where "12345" is the id. Crazy!

I am missing something very basic for sure, but I have NEVER seen Rails try to call an object id a format.

Here is the routes entry:

map.resources :part_types, :collection => { :part_list => :get }

and here is the result from "rake routes"

POST   /part_types(.:format)    {:controller=>"part_types", :action=>"create"}

Notice the absence of any sort of id!

The route with the name part_types refers to the index action if the method is GET and to the create action if the method is POST . Neither of those actions have parameterized paths (in contrast to show which should look like /part_types/:id ). create is supposed to create a new record and return its id - you usually don't pass them in the request as unique id generation is easier on the server.

Your first argument will be interpreted as the format because the route does not take any parameters. Compare this to the following:

  • part_type_path(1) should return /part_types/1
  • part_type_path(1, :json) should return /part/types/1.json .

Check actionpack/lib/action_dispatch/routing/mapper.rb to see how resources is defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM