Reputation: 851
I'm a complete Rails newbie and I have a Rails Question about controllers and actions. In my controller, I have an action named vote. The code is as follows.
def vote
@item = Item.find(params[:id])
@item.increment(:votes)
@item.save
render :action => show
end
I have a button on a "show" view that activates this action as follows
<%= button_to "Vote", :action => "vote", :id => @item.id, %>
My issue is that when the button is pressed, I don't want the application to try going to /items/:id/vote. I just want the code executed, then return back to the show view. I really appreciate all the advice!
Upvotes: 1
Views: 3117
Reputation: 1212
Check out redirect_to
, at the end of this code simply call redirect_to with a url or a path to go to and the user will be sent wherever you like.
If this vote function is in the same controller as show you can do
def vote
@item = Item.find(params[:id])
@item.increment(:votes)
@item.save
redirect_to :action => 'show'
end
This would send them back to your show controller (I would also look into Rails path and url functions - they're extremely helpful)
Upvotes: 3
Reputation: 8202
The application has to go to items/:id/vote, that's the request you're sending. Add that action to your routes file.
If you're using restful routes for items, you can do this:
resources :items do
member do
post 'vote'
end
end
Source for the above code is at http://guides.rubyonrails.org/routing.html#resource-routing-the-rails-default.
I would, however, suggest you take a minute to think and acquaint yourself with the concept of resources. Is a vote a resource? If so, you might be better off creating a VotesController and sticking to the built-in routes.
Hope this helps.
Upvotes: 1