Programming

부분이 존재하는지 확인하는 Rails 함수가 있습니까?

procodes 2020. 8. 22. 12:25
반응형

부분이 존재하는지 확인하는 Rails 함수가 있습니까?


존재하지 않는 부분을 렌더링하면 예외가 발생합니다. 렌더링하기 전에 부분이 존재하는지 확인하고, 존재하지 않는 경우 다른 것을 렌더링하겠습니다. .erb 파일에서 다음 코드를 수행했지만이 작업을 수행하는 더 좋은 방법이 있어야한다고 생각합니다.

    <% begin %>
      <%= render :partial => "#{dynamic_partial}" %>
    <% rescue ActionView::MissingTemplate %>
      Can't show this data!
    <% end %>

현재 저는 Rails 3 / 3.1 프로젝트에서 다음을 사용하고 있습니다.

lookup_context.find_all('posts/_form').any?

내가 본 다른 솔루션에 비해 장점은 레일 루트가 아닌 모든 뷰 경로에서 볼 수 있다는 것입니다. 레일 엔진이 많기 때문에 이것은 나에게 중요합니다.

이것은 Rails 4에서도 작동합니다.


나도 이것으로 고군분투하고 있었다. 이것은 내가 사용한 방법입니다.

<%= render :partial => "#{dynamic_partial}" rescue nil %>

기본적으로 부분이 존재하지 않으면 아무것도하지 않습니다. 그래도 부분이 누락 된 경우 무언가를 인쇄하고 싶습니까?

편집 1 : 오, 나는 독해에 실패했습니다. 다른 것을 렌더링하고 싶다고 말씀하셨습니다. 그렇다면 이건 어때?

<%= render :partial => "#{dynamic_partial}" rescue render :partial => 'partial_that_actually_exists' %>

또는

<%= render :partial => "#{dynamic_partial}" rescue "Can't show this data!" %>

편집 2 :

대안 : 부분 파일의 존재 확인 :

<%= render :partial => "#{dynamic_partial}" if File.exists?(Rails.root.join("app", "views", params[:controller], "_#{dynamic_partial}.html.erb")) %>

뷰 내부에서 template_exists? 작동하지만 호출 규칙은 단일 부분 이름 문자열로 작동하지 않고 대신 template_exists? (이름, 접두사, 부분)를 사용합니다.

경로에서 부분을 확인하려면 : app / views / posts / _form.html.slim

사용하다:

lookup_context.template_exists?("form", "posts", true)

Rails 3.2.13에서 컨트롤러에 있다면 다음을 사용할 수 있습니다.

template_exists?("#{dynamic_partial}", _prefixes, true)

template_exists?에 위임 lookupcontext당신이 볼 수 있듯이,AbstractController::ViewPaths

_prefixes 컨트롤러의 상속 체인의 컨텍스트를 제공합니다.

true 부분을 ​​찾고 있기 때문입니다 (일반 템플릿을 원한다면이 인수를 생략 할 수 있습니다).

http://api.rubyonrails.org/classes/ActionView/LookupContext/ViewPaths.html#method-i-template_exists-3F


나는 이것이 답을 얻었고 백만 년이라는 것을 알고 있지만, 여기에 내가 이것을 어떻게 고쳤는지가 있습니다 ...

레일즈 4.2

먼저 이것을 application_helper.rb에 넣습니다.

  def render_if_exists(path_to_partial)
    render path_to_partial if lookup_context.find_all(path_to_partial,[],true).any?
  end

그리고 지금 전화하는 대신

<%= render "#{dynamic_path}" if lookup_context.find_all("#{dynamic_path}",[],true).any? %>

난 그냥 전화 해 <%= render_if_exists "#{dynamic_path}" %>

도움이 되길 바랍니다. (rails3에서 시도하지 않았습니다)


저는이 패러다임을 여러 번 사용하여 큰 성공을 거두었습니다.

<%=
  begin
    render partial: "#{dynamic_partial}"
  rescue ActionView::MissingTemplate
    # handle the specific case of the partial being missing
  rescue
    # handle any other exception raised while rendering the partial
  end
%>

위 코드의 이점은 특정 경우를 견인 할 수 있다는 것입니다.

  • 부분이 실제로 누락되었습니다.
  • 부분이 존재하지만 어떤 이유로 오류가 발생했습니다.

코드 <%= render :partial => "#{dynamic_partial}" rescue nil %>나 일부 파생물 만 사용하면 부분이 존재할 수 있지만 예외가 발생하여 조용히 먹히고 디버깅을위한 고통의 원인이됩니다.


자신의 도우미는 어떻습니까?

def render_if_exists(path, *args)
  render path, *args
rescue ActionView::MissingTemplate
  nil
end

참고 URL : https://stackoverflow.com/questions/3559419/is-there-any-rails-function-to-check-if-a-partial-exists

반응형