简体   繁体   中英

Ruby on Rails: Can I do a “link_to” to call a create action?

How would I correctly call the create action from a link_to? I'm using REST (map.resources :recipes). Here's the create action:

def create
  recipe = Recipe.create(:name => "French fries")
  redirect_to recipe
end

For example, I thought something like this might work:

<%= link_to "Create a default recipe", recipe_path, :method => :post %>

I'm not sure if that's a recommended (or even correct) way to do it. Any idea?

That should work if you substitute recipes_path for recipe_path .

If you look at the output of rake routes , you should see something like:

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

That's a clue that the URL helper ("recipes_path"), for the create action is made up from the controller name with _path tacked on the end, using :method => :post . The same path using :method => :get (which is the default) maps to the index action.

Remember this won't work if Javascript is disabled, because Rails is actually adding an on_click handler that creates a form to do the POST. Same goes for delete links with the :confirm option.

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