私はレールに不慣れで、上/下の投票ボタンを作成しようとしています(明確にするために、今のところテキストリンクとして実装されています)。ただし、どのリンクをクリックしても、名前が異なるにもかかわらず、最初のリンクのアクションが呼び出されます。
ここのドキュメントと回答を何度も読み、一日中それに取り組んできましたが、レールが違いを認識できない理由をまだ理解できません。
ルート
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 ブロックを削除すると、ルートが見つかりませんが、match ステートメントは機能するはずです (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 に 2 つのルートがある Rake ルート
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
別の質問の解決策に基づいて、投稿と投稿の両方を使用してみました