让路线破碎

时间:2015-05-18 18:52:25

标签: ruby-on-rails ruby

在对帖子进行投票或投票时,我一直收到以下错误:

Routing Error
No route matches [GET] "/posts/181/up-vote"   

选民部分:

<% if policy( Vote.new ).create? %>
      <div class="vote-arrows pull-left">
        <div>
          <%= link_to " ",
            post_up_vote_path(post),
            class: "glyphicon glyphicon-chevron-up #{(current_user.voted(post) && current_user.voted(post).up_vote?) ? 'voted' : '' }", method: :post do %>
        </div>
        <div>
          <strong><%= post.points %></strong>
        </div>
        <div>
          <%= link_to " ",
            post_down_vote_path(post),
            class: "glyphicon glyphicon-chevron-down #{(current_user.voted(post) && current_user.voted(post).down_vote?) ? 'voted' : '' }", method: :post do %>
        </div>
      </div>
    <% end %>

投票控制人:

class VotesController < ApplicationController
  before_action :load_post_and_vote

  def up_vote
    update_vote!(1)
    redirect_to :back
  end

  def down_vote
    update_vote!(-1)
    redirect_to :back
  end
    private
    def load_post_and_vote
      @post = Post.find(params[:post_id])
      @vote = @post.votes.where(user_id: current_user.id).first
    end

    def update_vote!(new_value)
      if @vote
        authorize @vote, :update?
        @vote.update_attributes(value: new_value)
      else
        @vote = current_user.votes.build(value: new_value, post: @post)
        authorize @vote, :create?
        @vote.save
      end
    end
  end

我在投票控制器中定义了一个向上和向下的方法。但是,它们是通过POST路由调用的。我需要把它作为:put或:down_vote ???

    Rails.application.routes.draw do
  get 'comments/create'

  devise_for :users
    resources :users, only: [:update]

  resources :topics do
    resources :posts, except: [:index]
  end

  resources :posts, only: [] do
    resources :comments, only: [:create, :destroy]
      resources :favorites, only: [:create, :destroy]

    post '/up-vote' => 'votes#up_vote', as: :up_vote
    post '/down-vote' => 'votes#down_vote', as: :down_vote
  end

  get 'about' => 'welcome#about' # Redirecting the about variable to a welcome/about
  get 'newpost' => 'posts#new'
  root to: 'welcome#index'

end

1 个答案:

答案 0 :(得分:2)

首先,您不应该使用GET来更改实体的状态,因为该动词应保持不变。 POST通常被保留用于创建实体(尽管它可以引起争议)。

PUT是更新实体的正确动词。

将您的链接更改为:

<%= link_to " ",
            post_up_vote_path(post),
            class: "glyphicon glyphicon-chevron-up #{(current_user.voted(post) && current_user.voted(post).up_vote?) ? 'voted' : '' }",
            method: :put do %>

然后,在您的routes.rb文件中,检查您是否有类似的内容:

resources :posts do
  member do
    put 'up-vote'
  end
end

有关详细信息,请查看以下精彩指南:http://guides.rubyonrails.org/routing.html

如果仍然无效,请检查带有方法PUT的表单是否由ActionView创建,方法是使用Chrome检查DOM。请在此处查看方法http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

  

此修饰符将动态创建HTML表单   ...   如果用户禁用了JavaScript,请求将回退到使用GET

检查:

  • 你没有一些JS代码崩溃
  • 您的浏览器未禁用JS
  • 在您尝试点击之前,
  • 页面已满载