Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up to invoke form helpers from Rails console

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.

like image 495
Peter Alfvin Avatar asked Jan 05 '14 16:01

Peter Alfvin


People also ask

What are Rails helpers used for?

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.


2 Answers

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
like image 196
Billy Chan Avatar answered Dec 15 '22 13:12

Billy Chan


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)
like image 23
willmanduffy Avatar answered Dec 15 '22 13:12

willmanduffy