복붙노트

[RUBY-ON-RAILS] 리디렉션을 통해 검증 레일

RUBY-ON-RAILS

리디렉션을 통해 검증 레일

나는 레일로 작성 짐승 포럼을 시도하고 내가 직면 계속 ​​문제의 예로서 이것을 사용합니다.

포럼은 주제 내에서 새 게시물을 만들 수있는 하단의 형태와 주제 / show 액션과 전망을 가지고있다.

양식을 제출하면 게시물로 이동 / 같은 주제 / 쇼로 리디렉션 및 다시 형태로하고 생성하고 검증 돌아 주제 / 쇼 리디렉션을 전달하고 유효성 검사가 실패하지만 경우, 벌금을 작동하는 경우 (본문 필드를 떠나) 작업이 => 새로운 : 없음 유효성 검사 오류로 ... 검증이 실패 정상적으로 경우 렌더링과 생성 / 무엇에 남아 있습니다.

리디렉션에서 손실되는 검증이 있고, 작업을 얻는 가장 좋은 방법은 무엇인가?

코드를 아래 참조 :

PostsController.rb

  def create
    @post = current_user.reply @topic, params[:post][:body]

    respond_to do |format|
      if @post.new_record?
        format.html { redirect_to forum_topic_path(@forum, @topic) }
        format.xml  { render :xml  => @post.errors, :status => :unprocessable_entity }
      else
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to(forum_topic_post_path(@forum, @topic, @post, :anchor => dom_id(@post))) }
        format.xml  { render :xml  => @post, :status => :created, :location => forum_topic_post_url(@forum, @topic, @post) }
      end
    end
  end

TopicsController.rb

  def show
    respond_to do |format|
      format.html do
        if logged_in?
          current_user.seen!
          (session[:topics] ||= {})[@topic.id] = Time.now.utc
        end
        @topic.hit! unless logged_in? && @topic.user_id == current_user.id
        @posts = @topic.posts.paginate :page => current_page
        @post  = Post.new
      end
      format.xml  { render :xml  => @topic }
    end
  end

주제 / 쇼보기

  <% form_for :post, :url => forum_topic_posts_path(@forum, @topic, :page => @topic.last_page) do |f| %>

  <%= f.error_messages %>

  <table width="100%" border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td rowspan="2" width="70%">
        <%= f.text_area :body, :rows => 8 %>
      </td>
      <td valign="top">
        <%= render :partial => "posts/formatting" %>
      </td>
    </tr>
    <tr>
      <td valign="bottom" style="padding-bottom:15px;">
       <%= submit_tag I18n.t('txt.views_topics.save_reply', :default => 'Save reply') %>
     </td>
   </tr>
  </table>
  <% end %>

많은 감사합니다.

해결법

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

    1.난 당신이 여기에 두 가지 문제가있다 생각합니다.

    난 당신이 여기에 두 가지 문제가있다 생각합니다.

    이러한 것들을 모두 연결되어 있습니다.

    검증 오류는 일반적으로 물체에 작용하는 error_msg_for 방법을 통해 표시됩니다. 일반적으로 저장할 수 없습니다 객체의 인스턴스 변수로 컨트롤러에 의해 제공했다. 동일한 인스턴스 변수 형태를 다시 채우기 위해 사용된다.

    리디렉션 동안 제어기는 일반적 PARAMS 해시를 사용하여 인스턴스 변수를 초기화한다. 정보가 분실 저장 실패 이유를 확인하는 데 사용 그래서. 일반 자원이 성공에 실패 리디렉션 저장에 렌더링,이 두 가지 일이 발생합니다.

    나는 확실하지 스레드를 만들 수있는 형태의 활성 레코드 모델의 경우 해요, 그래서 내가 너무 잘 야수를 모른다. 그러나 다음이 문제를 해결하려면 방법에 대한 아이디어를 당신에게 제공 할 것입니다. 당신이 그것을 업데이트 유지하기 위해 도구를 사용하고 만약 그렇다면 그것은, 야수 플러그인의 로컬 복사본을 수정 포함 것, 변경 사항이 길을 잃을 수 있습니다.

    나는 당신의 검증 문제를 얻으려면이 다음과 같은 방법을 사용하고있다. 당신이에 대해 얘기하고 형태를 가정하는 것은 그들이 모든 것을 당신이 양식을 다시 채울 필요를 제공해야 nmodel을 기반으로합니다.

    기본적으로 당신은 clone_with_errors를 사용하여 플래시 해시에 오류가있는 개체의 단순 복사본을 저장합니다. 당신은 얕은 복사를 사용하거나 다른 여러 단체와 기록에 대한 오류를 표시 할 때 당신은 문제로 실행하겠습니다.

    그 때 나는 오류 메시지 HTML을 구축 할 수있는 표준 error_msg_for과 같은 옵션을 걸립니다 my_error_msg_for를 사용합니다. 어떤 이유로 표준 error_msg_for 방법은 해시에 저장된 오브젝트 작동하지 않았기 때문에 나는 단지 그것을 썼다. 그것은 괴로워했다 error_msg_for의 공식 소스 버전과 거의 동일합니다.

    /app/controllers/examples_controller.rb

    class ExamplesController < ApplicationController
      def update
        ...
    
        if @example.save 
          regular action
        else
          flash[:errors] = clone_with_errors(@example)
          respond_to do |format|
            format.html redirect_to(@example)
          end
        end
    end
    

    /app/views/examples/show.html.erb

    <div id="error">
            <% if flash[:errors] && !flash[:errors].empty? then -%>
    
            <p ><%= my_error_msg_for flash[:errors] %></p>
    
            <% end -%>
    </div>
    ...
    

    여기에 당신이 모든 작업을 내리는 데 필요한 코드입니다.

    application_controller.rb

     def clone_with_errors(object)
        clone = object.clone
        object.errors.each{|field,msg| clone.errors.add_to_base(msg)}
        return clone
      end
    

    application_helper.rb

     def _error_msg(*params)
    
        options = params.extract_options!.symbolize_keys
        if object = options.delete(:object)
          objects = [object].flatten
        else
          objects = params.collect {|object_name| instance_variable_get("@#{object_name}") }.compact
        end
        count   = objects.inject(0) {|sum, this| sum + this.errors.count }
        unless count.zero?
          html = {}
          [:id, :class].each do |key|
            if options.include?(key)
              value = options[key]
              html[key] = value unless value.blank?
            else
              html[key] = 'errorExplanation'
            end
          end
          options[:object_name] ||= params.first
          options[:header_message] = "#{pluralize(count, 'error')} prohibited this #{options[:object_name].to_s.gsub('_', ' ')} from being saved" unless options.include?(:header_message) && !options[:header_messag].nil?
          options[:message] ||= 'There were problems with the following fields:' unless options.include?(:message) && !options[:message].nil?
          error_messages = objects.sum {|this| this.errors.full_messages.map {|msg| content_tag(:li, msg) } }.join
    
          contents = ''
          contents << content_tag(options[:header_tag] || :h2, options[:header_message]) unless options[:header_message].blank?
          contents << content_tag(:p, options[:message]) unless options[:message].blank?
          contents << content_tag(:ul, error_messages)
    
          content_tag(:div, contents, html)
        else
                                            ''
        end
    
      end
    
      def my_error_msg_for(params)
        _error_msg_test :object_name => params[:object].class.name.gsub(/([a-z])([A-Z])/,'\1 \2').gsub(/_/, " "),
        :object => params[:object], :header_message => params[:header_message], :message => params[:message]
      end
    
  2. ==============================

    2.나는 짐승에 대해 아무것도 몰라 두려워 해요,하지만 당신은 리디렉션 할 때 일반적으로, 모든 손실됩니다 말하기. 그것은 새로운 페이지 요청, 그리고 그것을 어딘가에 저장되어있어하지 않는 한 모든 리셋 (일반적으로, 데이터베이스 또는 세션을.)

    나는 짐승에 대해 아무것도 몰라 두려워 해요,하지만 당신은 리디렉션 할 때 일반적으로, 모든 손실됩니다 말하기. 그것은 새로운 페이지 요청, 그리고 그것을 어딘가에 저장되어있어하지 않는 한 모든 리셋 (일반적으로, 데이터베이스 또는 세션을.)

    당신이 형태의 참조하는 경향이 일반적인 흐름은 객체가 저장되어있는 경우 리디렉션하지만 저장이 실패 할 경우 렌더링하는 것입니다. 뷰 파일은 컨트롤러에 어떤 변수 것이왔다 세트를 선택할 수 있습니다 - 일반적으로 저장하고 확인 메시지하지 않았다 객체를 포함 할 것이다.

    죄송합니다 그 문제가 해결되지 않는, 그러나 희망 그것은 당신에게 몇 가지 단서를 제공 할 수 있습니다.

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

    3.매우 유사한 질문에 대한 내 대답은 최근 여기에 StackOverflow에 게시 된 redirect_to 대 렌더링 토론에 장점과 단점의 숫자를 다룹니다. 나는 사람이 토론에 추가 할 다른 장점 / 단점이 있다면 듣고 싶네요.

    매우 유사한 질문에 대한 내 대답은 최근 여기에 StackOverflow에 게시 된 redirect_to 대 렌더링 토론에 장점과 단점의 숫자를 다룹니다. 나는 사람이 토론에 추가 할 다른 장점 / 단점이 있다면 듣고 싶네요.

  4. from https://stackoverflow.com/questions/1536428/rails-validation-over-redirect by cc-by-sa and MIT license