无法在视图中触发此控制器操作(它不是默认的Rails RESTful操作)
问题描述:
我有一个名为的控制器votes_controller.rb。在该文件中有下列行为:无法在视图中触发此控制器操作(它不是默认的Rails RESTful操作)
class VotesController < ApplicationController
def vote_up
@post = Post.find(params[:post_id])
vote_attr = params[:vote].merge :user_id => current_user.id, :polarity => 1
@vote = @post.votes.create(vote_attr)
end
(等)
我想触发在视图中vote_up
行动:
的意见/职位/ show.html。 ERB::
<%= link_to "Vote Up", ??? %>
这里是整个文件,以防万一:
<h2>posts show</h2>
<span>Title: <%= @post.title %></span><br />
<span>Content: <%= @post.content %></span><br />
<span>User: <%= @post.user.username %></span><br />
<%= link_to "Vote Up", ??? %>
<h2>Comments</h2>
<% @post.comments.each do |comment| %>
<p>
<b>Comment:</b>
<%= comment.content %>
</p>
<p>
<b>Commenter</b>
<%= link_to comment.user.username, comment.user %>
</p>
<% end %>
<h2>Add a comment:</h2>
<%= form_for([@post, @post.comments.build]) do |f| %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<% if current_user.id == @post.user_id %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<% end %>
<%= link_to 'Back', posts_path %>
我不知道该输入什么?部分(我还想使它的工作为:remote
。我的意图是触发该操作而不刷新页面)。
我必须在routes.rb
中添加一些东西吗?
有什么建议吗?
答
您必须在routes.rb
中定义路线。使用命名路线在视图中易于使用。喜欢的东西:
get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'
因此,现在就可以在视图
<%= link_to "Vote Up", vote_up_path(@post) %>
,并在控制器使用
def vote_up
@post = Post.find(params[:id])
...
end
你为什么用'GET'代替'map'? – alexchenco 2012-02-05 10:46:35
你的意思是代替'match'? 'get'votes /:id/vote_up'=>'votes#vote_up'是'match'投票的简写版本/:id/vote_up'=>'votes#vote_up',:via =>:get'。这个url只在你的例子中通过'GET'调用,所以我只声明了'GET'route。 – Baldrick 2012-02-05 11:01:21
哦,谢谢!它工作完美。 – alexchenco 2012-02-05 11:08:03