开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜