Rails 컨트롤러에서 도우미 메서드를 호출하려고 할 때 NoMethodError
NoMethodError
내 컨트롤러 클래스 중 하나에서 내 도우미 모듈 중 하나에 정의 된 메서드에 액세스하려고 할 때 오류가 발생합니다 . 내 Rails 애플리케이션은 아래와 같이 기호 가있는 helper
클래스 메서드를 사용합니다 :all
.
class ApplicationController < ActionController::Base
helper :all
.
.
end
내 이해는 이것이 내 모든 컨트롤러 클래스가 app / helpers 디렉토리 내의 모든 도우미 모듈을 자동으로 포함하므로 모든 메서드를 컨트롤러에 혼합한다는 것입니다. 이 올바른지?
include
컨트롤러 내에서 명시 적 으로 도우미 모듈을 사용하면 모든 것이 올바르게 작동합니다.
helper :all
모든 헬퍼 (예, 모두)를 뷰에서 사용할 수 있도록합니다. 컨트롤러에 포함하지는 않습니다.
도우미와 컨트롤러간에 일부 코드를 공유하려는 경우 도우미는 UI 코드이고 컨트롤러는 컨트롤러 코드이므로 그다지 바람직하지 않습니다. 컨트롤러에 도우미를 포함하거나 별도의 모듈을 만들어 포함 할 수 있습니다. 컨트롤러와 도우미도 마찬가지입니다.
템플릿 엔진에 이미 포함 된 도우미 메서드를 사용하려면 :
- Rails 2 :
@template
변수를 사용합니다 . - Rails 3 : 멋진 컨트롤러 방법이 있습니다.
view_context
컨트롤러 메서드에서 'number_to_currency'를 호출하는 사용 예 :
# rails 3 sample
def controller_action
@price = view_context.number_to_currency( 42.0 )
end
# rails 2 sample
def controller_action
@price = @template.number_to_currency( 42.0 )
end
컨트롤러와 도우미 / 뷰간에 메서드를 공유해야하는 경우 컨트롤러 상단의 'helper_method'를 통해 정의 할 수 있습니다.
class ApplicationController < ActionController::Base
helper_method :my_shared_method
...
def my_shared_method
#do stuff
end
end
도움이되기를 바랍니다
컨트롤러의 도우미 메서드
도우미 메서드를 얻는 한 가지 방법은 도우미 파일을 포함하는 것입니다.
include LoginHelper
cool_login_helper_method(x,y,z)
그러면 해당 도우미 모듈의 모든 메서드가 컨트롤러의 범위에 포함됩니다. 항상 좋은 것은 아닙니다. 범위를 별도로 유지하려면 개체를 만들고 해당 도우미의 기능을 포함하고이를 사용하여 메서드를 호출합니다.
login_helper = Object.new.extend(LoginHelper)
login_helper.cool_login_helper_method(x,y,z)
도우미 : 모두
helper :all
모든 헬퍼 모듈의 모든 헬퍼 메소드를 모든 뷰 에서 사용할 수 있도록 하지만 컨트롤러에 대해서는 아무 작업도 수행하지 않습니다. 도우미 메서드는 뷰에서 사용하도록 설계되었으며 일반적으로 컨트롤러에서 액세스해서는 안되기 때문입니다. 최신 버전의 Rails에서이 옵션은 기본적으로 모든 컨트롤러에 대해 항상 켜져 있습니다.
Rails 3의 경우 view_context
컨트롤러에서 다음 방법을 사용합니다 .
def foo
view_context.helper_method
...
예 : http://www.christopherirish.com/2011/10/13/no-view_context-in-rails-3-1-changes/
이것이 가장 필요하다고 생각되는 시간은 플래시 또는 사용자 정의 오류 검사기를 작성하는 것입니다. 어떤 상황에서는 플래시 메시지에서 link_to 도우미와 같은 것을 사용하는 것이 좋습니다. 다음 솔루션을 사용하여 ActionView 도우미를 컨트롤러로 가져옵니다. 위에서 언급했듯이 이것은 MVC 분리를 깨뜨 리므로 다른 사람이 더 나은 아이디어를 가지고 있다면 알려주십시오!
ApplicationController 아래에 다음을 추가하십시오.
class Something
include Singleton
include ActionView::Helpers::UrlHelper
end
그리고 ApplicationController 내부에서
def foo
Something.instance
end
마지막으로 도우미 코드에 액세스하려는 컨트롤러에서 :
messages << "<li class='error'>Your have an Error!<%= foo.link_to('Fix This', some_path) %></li>"
어떤 식 으로든 도움이되기를 바랍니다.
helpers 메서드 를 사용하는 것이 더 깔끔 할 것입니다 .
class FooController < ActionController::Base
def action
self.class.helpers.helper_method arg
end
end
컨트롤러에서 @template 변수를 사용하여 모든 도우미에 액세스 할 수 있습니다.
@ template.my_super_helper
컨트롤러는 도우미 메서드에 자동으로 액세스 할 수 없습니다. 앱 컨트롤러에 포함해야합니다.
모듈 ApplicationHelper
def hello_message
"Hello World"
end
end
class ApplicationController < ActionController::Base
include ApplicationHelper
def message
hello_message
end
end
Helpers are to be used with templates, ie. views, not in controllers. That's why you can't access the method. If you'd like to share a method between two controllers, you'd have to define it in ApplicationController, for instance. helper :all says that any method you define in any helper file in app/helpers directory will be available to any template.
There are two ways to do this: either to create a module or use @template variable. Check this out for more details http://www.shanison.com/?p=305
If you only have ApplicationHelper inside your app/helpers
folder than you have to load it in your controller with include ApplicationHelper
. By default Rails only load the helper module that has the same name as your controller. (e.g. ArticlesController will load ArticlesHelper). If you have many models (e.g. Articles; Posts; Categories) than you have to upload each one in you controller. the docs
Helper
module PostsHelper
def find_category(number)
return 'kayak-#{number}'
end
def find_other_sport(number)
"basketball" #specifying 'return' is optional in ruby
end
end
module ApplicationHelper
def check_this_sentence
'hello world'
end
end
Example Controller
class ArticlesController < ApplicationController
include ApplicationHelper
include PostsHelper
#...and so on...
def show#rails 4.1.5
#here I'm using the helper from PostsHelper to use in a Breadcrumb for the view
add_breadcrumb find_other_sport(@articles.type_activite), articles_path, :title => "Back to the Index"
#add_breadcrumb is from a gem ...
respond_with(@articles)
end
end
If you change your application_controller.rb file to this...
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
end
...then all helpers will be available to all controllers.
'Program Tip' 카테고리의 다른 글
숭고한 텍스트 2에서 명령 모드 종료 (0) | 2020.10.22 |
---|---|
둘 이상의 부울이 "참"인지 정중하게 결정 (0) | 2020.10.22 |
문자열 내에서 변수 사용 (0) | 2020.10.22 |
CollectionView sizeForItemAtIndexPath가 호출되지 않았습니다. (0) | 2020.10.22 |
장치에 데이터 로깅 및 로그 검색 (0) | 2020.10.22 |