Rails button_to包含图像和动作

时间:2015-04-25 17:45:21

标签: ruby-on-rails

我想显示带图像的按钮。 我有这个代码

<%= image_submit_tag "down.png", controller: "posts", action: "votedown", post_id: post.id, topic_id: post.topic_id, class: "xta" %>

它可以正常显示,但没有调用行动“投票”

在我的路线中我有

post '/votedown', to: 'posts#votedown

请同时建议是否有其他方法可以使用参数和图像“down.png”调用此方法进行投票。

1 个答案:

答案 0 :(得分:1)

image_submit_tag must be used in conjunction with a form - 它只是一个普通的html <input type="submit">按钮。

您可能还想将路线定义更改为更安静的内容:

patch '/posts/:id/votedown' => "posts#votedown", as: 'votedown_post'

这使得此路由更明显地作用于帖子 - 我们使用PATCH方法,因为我们正在更改资源而不是创建新资源。

使用我们的新路线,我们可以简单地创建一个表单:

<%= form_for(@post, url: votedown_post_path(@post) ) do |f| %>
  <%= image_submit_tag "down.png", class: "xta" %>
<% end %>

请注意,您无需为帖子ID添加输入,因为它将以params[:id]的形式提供。

另一种方法是使用Rails unobstructive javascript驱动程序创建一个向PATCH发送'/posts/:id/votedown'请求的链接或按钮。

<%= link_to image_tag("down.png", class: "xta"), votedown_post_path(@post), method: :patch %>
相关问题