user502052
user502052

Reputation: 15259

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.

Upvotes: 0

Views: 7123

Answers (3)

rajith
rajith

Reputation: 112

You can try this.It works in my case.

 <%= link_to(t(:delete), :action => 'destroy', :method => :delete, :id => @post.id ) %> 

Upvotes: 3

John Douthat
John Douthat

Reputation: 41179

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) %>

Upvotes: 0

Kyle Macey
Kyle Macey

Reputation: 8154

I would stick by the advisement of your comments, but the syntax would be:

<%= link_to "Delete", {:action => 'delete', :id => @post.id} %>

Upvotes: 0

Related Questions