rails 3- Having Action in Controller Without View

天涯浪子 提交于 2019-12-24 11:15:32

问题


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!


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/8830017/rails-3-having-action-in-controller-without-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!