복붙노트

[RUBY-ON-RAILS] 어떻게 도우미 안쪽 컨트롤러를 사용하는 - 난간

RUBY-ON-RAILS

어떻게 도우미 안쪽 컨트롤러를 사용하는 - 난간

난 당신이보기 안에 도우미를 사용하기로되어있다 실현하면서 내가 반환에 JSON 객체를 짓고 있어요, 나는 내 컨트롤러에 도우미가 필요합니다.

그것은 다음과 같이 약간 간다 :

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

어떻게 내 html_format 도우미를 액세스 할 수 있습니까?

해결법

  1. ==============================

    1.참고 :이 작성되었다 레일 2 일 내에 받아 들여진 다시; 요즘 그로서의의 대답은 길을 가야하는 것입니다.

    참고 :이 작성되었다 레일 2 일 내에 받아 들여진 다시; 요즘 그로서의의 대답은 길을 가야하는 것입니다.

    옵션 1 : 아마 가장 간단한 방법은 컨트롤러에 도우미 모듈을 포함하는 것입니다 :

    class MyController < ApplicationController
      include MyHelper
    
      def xxxx
        @comments = []
        Comment.find_each do |comment|
          @comments << {:id => comment.id, :html => html_format(comment.content)}
        end
      end
    end
    

    옵션 2 : 아니면 클래스 함수와 도우미 메서드를 선언하고 너무 좋아 사용할 수 있습니다 :

    MyHelper.html_format(comment.content)
    

    당신이 인스턴스 기능과 클래스 기능을 모두로 사용할 수 있도록하려면, 당신은 당신의 도우미의 두 버전을 선언 할 수 있습니다 :

    module MyHelper
      def self.html_format(str)
        process(str)
      end
    
      def html_format(str)
        MyHelper.html_format(str)
      end
    end
    

    도움이 되었기를 바랍니다!

  2. ==============================

    2.당신이 사용할 수있는

    당신이 사용할 수있는

  3. ==============================

    3.레일에서 5 컨트롤러에 helpers.helper_function를 사용합니다.

    레일에서 5 컨트롤러에 helpers.helper_function를 사용합니다.

    예:

    def update
      # ...
      redirect_to root_url, notice: "Updated #{helpers.pluralize(count, 'record')}"
    end
    

    출처 : 다른 대답에 @Markus에 의해 코멘트에서. 나는 깨끗한 쉽게 솔루션이기 때문에 그의 대답이 자신의 대답을받을 자격.

    참조 : https://github.com/rails/rails/pull/24866

  4. ==============================

    4.내 문제는 옵션으로 해결 1. 아마 가장 간단한 방법은 컨트롤러에 도우미 모듈을 포함하는 것입니다 :

    내 문제는 옵션으로 해결 1. 아마 가장 간단한 방법은 컨트롤러에 도우미 모듈을 포함하는 것입니다 :

    class ApplicationController < ActionController::Base
      include ApplicationHelper
    
    ...
    
  5. ==============================

    5.도우미가 (단지) 컨트롤러에서 사용하는 경우 일반적으로, 나는 클래스와 ApplicationController의 인스턴스 메서드로 선언하는 것을 선호합니다.

    도우미가 (단지) 컨트롤러에서 사용하는 경우 일반적으로, 나는 클래스와 ApplicationController의 인스턴스 메서드로 선언하는 것을 선호합니다.

  6. ==============================

    6.레일에 5+ 당신은 단순히 간단한 예와 함께 아래에 입증 된 바와 같이 기능을 사용할 수 있습니다 :

    레일에 5+ 당신은 단순히 간단한 예와 함께 아래에 입증 된 바와 같이 기능을 사용할 수 있습니다 :

    module ApplicationHelper
      # format datetime in the format #2018-12-01 12:12 PM
      def datetime_format(datetime = nil)
        if datetime
          datetime.strftime('%Y-%m-%d %H:%M %p')
        else
          'NA'
        end
      end
    end
    
    class ExamplesController < ApplicationController
      def index
        current_datetime = helpers.datetime_format DateTime.now
        raise current_datetime.inspect
      end
    end
    
  7. ==============================

    7.

    class MyController < ApplicationController
        # include your helper
        include MyHelper
        # or Rails helper
        include ActionView::Helpers::NumberHelper
    
        def my_action
          price = number_to_currency(10000)
        end
    end
    

    레일에서 5+ 간단하게 사용할 헬퍼 (helpers.number_to_currency (10000))

  8. from https://stackoverflow.com/questions/5130150/rails-how-to-use-a-helper-inside-a-controller by cc-by-sa and MIT license