I'd like to experiment with using form helpers inside the Rails console, but my simple minded approach of doing extend ActionView::Helpers::FormHelper
didn't work. For example, subsequently calling form_for
resulted in the error NoMethodError: undefined method 'dom_class' for main:Object
. Using include
produces the same results.
Is there an "easy" way to enable me to call form helpers from the console? I'd prefer to do this without any dependency on controller or view files, if possible.
Basically helpers in Rails are used to extract complex logic out of the view so that you can organize your code better. I've seen two benefits for using helpers in my experience so far: Extract some complexity out of the view. Make view logic easier to test.
Peter, I'm happy to solve your problem.
For simple view helpers, it's very easy
> app.helper.link_to 'root', app.root_path
# <a href = ....> # as expected
However your specific case is not that easy as form_for needs view_context
and then a controller instance to work.
# Get a controller instance at first. Must do it.
# Without this step `app.controller` is nil
> app.get app.root_path
# Use an instance variable but not variable!
> @user = User.last
# Get the view
# Note you need to take the trouble to define url manually
# because console can only reach path through app instance
> app.controller.view_context.form_for(@user, url: app.user_path(@user)){|f| f.input :name}
# Job done
You need to use include, not extend:
irb(main):007:0> include ActionView::Helpers::FormHelper
=> Object
irb(main):008:0> form_for
ArgumentError: wrong number of arguments (0 for 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With