2014-01-05 128 views
4

我想嘗試在Rails控制檯內使用窗體幫助器,但是我的簡單方法做到extend ActionView::Helpers::FormHelper沒有奏效。例如,隨後調用form_for導致錯誤NoMethodError: undefined method 'dom_class' for main:Object。使用include產生相同的結果。設置從Rails控制檯調用窗體幫助器

是否有一種「簡單」的方式讓我能夠從控制檯調用窗體幫助器?如果可能的話,我寧願在不依賴控制器或查看文件的情況下執行此操作。

回答

4

彼得,我很高興爲您解決問題。

對於簡單的視圖助手,它很容易

> app.helper.link_to 'root', app.root_path 
# <a href = ....> # as expected 

但是您的具體情況不是那麼容易的,需要的form_for和view_context然後一個控制器實例工作。

# 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 
+0

彼得,歡呼! :) –

3

您需要使用包括沒有延伸:

irb(main):007:0> include ActionView::Helpers::FormHelper 
=> Object 
irb(main):008:0> form_for 
ArgumentError: wrong number of arguments (0 for 1) 
+0

查看更新的問題。問題不在於調用方法的能力。問題是滿足方法的依賴性。 –

+0

啊,我沒有看到那部分。你可以嘗試這樣的事情嗎? http://6brand.com/undefined-method-dom_class.html – willmanduffy

相關問題