AdamNYC
AdamNYC

Reputation: 20415

Rails button_to to trigger an action in Model directly

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 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.

Upvotes: 2

Views: 2945

Answers (2)

mu is too short
mu is too short

Reputation: 434665

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.

Upvotes: 6

Srdjan Pejic
Srdjan Pejic

Reputation: 8202

  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.

Upvotes: 2

Related Questions