开发者

Rails button_to to trigger an action in Model directly

开发者 https://www.devze.com 2023-04-10 04:16 出处:网络
I would like to allow user to cancel his Event by clicking a button on show page. I have a method cancel in Event model, but don\'t want to create a method cancel in Controller if I don\'t have to.

I would like to allow user to cancel his Event by clicking a button on show page. I have a method cancel in Event model, but don't want to create a method cancel in Controller if I don't have to.

My questions are:

  1. Is it 开发者_Go百科a good idea to invoke a method in the model directly from view in this case?
  2. If it is OK, then how should I do it using button_to?

Thank you.


No, trying to invoke a model method directly isn't a good idea. The Rails routing system routes to controllers so it simply won't work (unless you want to do a lot more work than simply writing a tiny controller).

If you call a model method from the view then that method will be executed while the view is being built and that happens before the user sees anything or has a chance to click a button. So you don't want to call your model's cancel method from your view, you want something to call your cancel method when the user performs an action, user actions are routed to controllers and controllers tell models what to do. You probably want a little bit of access control as well and that's generally handled at the controller level.


  1. No, it's not a good idea.
  2. Irrelevant, since it's not a good idea.

You can hook the button_to to the update action in the EventsController if the Event model has states or to the destroy action if cancelling the event means removing it.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号