2012-02-04 69 views
0

我有一個名爲的控制器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中添加一些東西嗎?

有什麼建議嗎?

回答

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 

Rails routing

+0

你爲什麼用'GET'代替'map'? – alexchenco 2012-02-05 10:46:35

+0

你的意思是代替'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

+0

哦,謝謝!它工作完美。 – alexchenco 2012-02-05 11:08:03

相關問題