我有一个名为 votes_controller.rb 的控制器。在该文件中,有以下操作:
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 %>
我不知道该怎么输入??? part(我也想让它工作为:remote
。我的目的是在不刷新页面的情况下触发操作)。
我是否必须在routes.rb
?
有什么建议吗?
答案 0 :(得分:2)
您必须在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