Setting up to invoke form helpers from Rails console

▼魔方 西西 提交于 2021-02-07 12:51:41

问题


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.


回答1:


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



回答2:


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)


来源:https://stackoverflow.com/questions/20935954/setting-up-to-invoke-form-helpers-from-rails-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!