我是 Rails 新手,正在尝试创建向上/向下投票按钮(为了清楚起见,现在实现为文本链接)。但是,无论单击哪个链接,它都会调用第一个链接的操作,尽管名称不同。
我已经一遍又一遍地阅读了这里的文档和答案,并且整天都在与它搏斗,但仍然无法理解为什么 rails 看不到差异,非常感谢任何帮助。
路线
Futurebot::Application.routes.draw do
resources :posts do
resources :comments
end
resources :posts do
member do
post 'delete'
post 'upVote'
post 'downVote'
end
end
match ':posts/:id/:upVote', :controller => 'posts', :action => 'upVote'
match ':posts/:id/:downVote', :controller => 'posts', :action => 'downVote'
如果我删除资源 :posts 块它找不到路线,但似乎匹配语句应该工作(这就是 url 的样子)
看法
<%= link_to "up: ", :action => 'upVote', :id => post.id %>
<%= link_to "down: ", :action => 'downVote', :id => post.id %>
控制器
def upVote
@post = Post.find(params[:id])
if @post.increment!(:score)
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
def downVote
@post = Post.find(params[:id])
if @post.decrement!(:score)
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
rake routes: with the 2 new routes commented out (so just the block is there)
up_vote_post POST /posts/:id/up_vote(.:format) posts#up_vo
te
down_vote_post POST /posts/:id/down_vote(.:format) posts#down_
vote
GET /posts(.:format) posts#index
POST /posts(.:format) posts#creat
e
GET /posts/new(.:format) posts#new
GET /posts/:id/edit(.:format) posts#edit
GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#updat
e
DELETE /posts/:id(.:format) posts#destr
oy
root /
posts#index
在 routes.rb 中使用两条路线耙路线
delete_post POST /posts/:id/delete(.:format) posts#delet
e
up_vote_post POST /posts/:id/up_vote(.:format) posts#up_vo
te
down_vote_post POST /posts/:id/down_vote(.:format) posts#down_
vote
GET /posts(.:format) posts#index
POST /posts(.:format) posts#creat
e
GET /posts/new(.:format) posts#new
GET /posts/:id/edit(.:format) posts#edit
GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#updat
e
DELETE /posts/:id(.:format) posts#destr
oy
/:post/up_vote/:id(.:format) post#up_vot
e
/:post/down_vote/:id(.:format) post#down_v
ote
root /
posts#index
添加的路线
match ':post/up_vote/:id' => "post#up_vote"
match ':post/down_vote/:id' => "post#down_vote"
更新
奇怪的是,如果我将路线更改为:
match ':post/:id/up_vote/' => "post#up_vote"
match ':post/:id/down_vote/' => "post#down_vote"
..因为这看起来像链接那么错误是
uninitialized constant PostController
我已经尝试根据另一个问题的解决方案同时使用帖子和帖子