How should I handle triggering an “action method” through a RESTful Controller?

怎甘沉沦 提交于 2020-02-06 09:27:10

问题


I am trying to keep my controllers nice a RESTful. One thing I keep running into is the need for a button or link on the site to trigger a specific event on a model. For example:

@user.ban!

Currently, I either make a custom named route on the users controller or if it's a more complex set of related actions, I create a new controller that acts on the same model as another "traditionally named" controller.

What is the best approach in this type of situation? What factors weigh into the decision?


回答1:


In your routes you would typically have a resources declaration looking something like this

resources :users

The best way to add a restfull route to this is to define a ban method in the users controller and add a member route to the users route so your route ends up looking like this

resources :users do
   member do
     post :ban, :pay, :whatever
   end
end

Use a memeber route for form post put actions, i.e. when using button_to or form_for (plus others) view helpers. Use collections for get requests (i.e. links)

Alternatively you could use <%= button_to 'Ban', @user %> then in the update action for the users controller check the commit params for the text ban and act accordingly Actually I use this myself occasionally like so

   if params[:commit] == 'Ban'
#    do something like calling a ban method setting a flash notice or alert and redirecting
   else
     normal controller flow
   end

Better still. Use i18n to display the text on the button and check the same i18n value against the commit param thereby leaving you free to change the text text on the button by updating the i18n yml file without breaking your controller code




回答2:


First off, what jamesw says is good. There are lots of details here...

http://guides.rubyonrails.org/routing.html#non-resourceful-routes http://guides.rubyonrails.org/routing.html#adding-more-restful-actions

... and I actually go with that for whatever unconventional routes I need. About the "factors that weigh into this decision," though... I would first ask myself if this eccentric action is absolutely needed, because more often than not Rails' "convention over configuration" policy comes in. From experience, I find that it's pretty rare for me to need atypical actions. I guess if you can justify it, though, don't feel guilty and go with it.

I have rarely ever had to make a whole 'nother controller, though.



来源:https://stackoverflow.com/questions/6796832/how-should-i-handle-triggering-an-action-method-through-a-restful-controller

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