Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 633
sjsc Avatar asked Apr 23 '10 21:04

sjsc


People also ask

How does link_to work in Rails?

Rails is able to map any object that you pass into link_to by its model. It actually has nothing to do with the view that you use it in. It knows that an instance of the Profile class should map to the /profiles/:id path when generating a URL.

How do I add a action in Rails?

When you click the Submit button in your form, it posts your data to the create action, which actually creates the record in the database. to your create action, since that is where you're actually saving the post to the database. ok,that means create is method which will be auto called at submit button !!

What is link_to?

method: symbol of HTTP verb - This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. Useful for having links perform a POST operation in dangerous actions like deleting a record (which search bots can follow while spidering your site).

How do I link pages in Ruby on Rails?

open index. html. erb file in app>>views>>home folder use in atom editor. After you open index file now add following HTML link code in that file and end with <br /> tag.


1 Answers

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.

like image 76
zetetic Avatar answered Sep 30 '22 12:09

zetetic