Ruby on Rails: link_to action, no routes

I get into Rails and try to add a voting feature to my blog setup from here: http://guides.rubyonrails.org/getting_started.html

In app / controller / posts_controller.rb I created this:

  def incvotes
    @post = Post.find(params[:id])
    post.update_attributes(:upvotes => 1 )
    format.html { redirect_to(@post, :notice => 'Vote counted.') }
    format.xml  { head :ok }
  end

In app / views / posts / index.html.erb I created this:

<%= link_to 'Vote', :controller => "posts", :action => "incvotes", :id => post.id %>

But the link gives an error

There are no route matches {: controller => "posts" ,: action => "incvotes" ,: id => 1}

Something is missing for me, but I don’t know what.

rake routes:

incvotes_post POST   /posts/:id/incvotes(.:format) {:action=>"incvotes", :controller=>"posts"}
        posts GET    /posts(.:format)              {:action=>"index", :controller=>"posts"}
              POST   /posts(.:format)              {:action=>"create", :controller=>"posts"}
     new_post GET    /posts/new(.:format)          {:action=>"new", :controller=>"posts"}
    edit_post GET    /posts/:id/edit(.:format)     {:action=>"edit", :controller=>"posts"}
         post GET    /posts/:id(.:format)          {:action=>"show", :controller=>"posts"}
              PUT    /posts/:id(.:format)          {:action=>"update", :controller=>"posts"}
              DELETE /posts/:id(.:format)          {:action=>"destroy", :controller=>"posts"}
   home_index GET    /home/index(.:format)         {:action=>"index", :controller=>"home"}
         root        /(.:format)                   {:action=>"index", :controller=>"home"}
+5
source share
4 answers

to try

= link_to "vote", incvotes_post_path(post), :method=>:post

and if that doesn't work, try changing the method: put

+3
source

, , , , . Rails URL-.

, , - :

resources :posts

, resources, - :

resources :posts do 
  member do
    post 'incvotes'
  end
end

, , incvotes, HTTP- , (/posts/14 - , /posts/ "" ). , , , /posts/14/incvotes, , .

EDIT:

, , 1 , POST ( , create update). , HTML- , URL-. , get 'incvotes' post 'incvotes'. , , !

+3

incvotes_post HTTP POST, HTTP GET.

( POST AJAX).

+1

button_to link_to:

:

<%= button_to 'Vote', incvotes_post_path(post) %>

config/routes.rb incvotes post:

resources :posts do 
  member do
    post 'incvotes'
  end
end

incvotes:

def incvotes
  # Something
  redirect_to :posts
end
0

All Articles