Call a custom controller action method from a 'link_to'
I am using Ruby on Rails 3 and I would like to state an action method in a my controller file so that in my view files I can use something like the following:
link_to("Delete", posts_path(@post.id), :method => :delete)
That is, 开发者_开发百科to have a link so that I can "directly" call and run an action method in my controller.
In the above code, for example, it is possible to call the destroy
method adding :method => :delete
.
You can try this.It works in my case.
<%= link_to(t(:delete), :action => 'destroy', :method => :delete, :id => @post.id ) %>
I would stick by the advisement of your comments, but the syntax would be:
<%= link_to "Delete", {:action => 'delete', :id => @post.id} %>
Change posts_path
to post_path
:
<%= link_to 'Destroy', post_path(post), :confirm => 'Are you sure?', :method => :delete %>
or, even better,
<%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %>
Also, to link to another action, add a route for it,
e.g. resources :posts, :member => [:mycustomaction]
and in your view <%= link_to("foobar", mycustomaction_post_path(post) %>
精彩评论