Cooper Maruyama
Cooper Maruyama

Reputation: 1612

Possible to use form_for in rails to call a model's method and pass arguments into it?

Let's say I had a model that looked something like this:

class SomeModel

  def method(var1, var2) do
    do.something.with(var1)
    do.something.with(var2)
  end

end

Is it possible to write a form_for within a view in rails that would call method when the person hits submit, and pass values that are set in the input fields as arguments to that method? Sorry if this is basic, but I can't seem to figure it out on my own.

Upvotes: 1

Views: 545

Answers (2)

Keith Johnson
Keith Johnson

Reputation: 730

This isn't always the case. You can hit a state_machine's status_events' methods with something like this:

"model[status_event]" => "do_stuff"

Which would trigger whatever block is associated with that event. But I haven't got this working with custom methods for some reason, not sure why...

Upvotes: 0

Meier
Meier

Reputation: 3880

form_for creates the html for a form. It does not handle the submit itself. When the user presses submit, a method in the controller is called.

In the controller method, you can call your model method. It is the right place, because it is the controllers job to handle the input parameters and manage which model object to call. The input fields are accessible in the params hash in the controller.

Upvotes: 1

Related Questions