2015-01-26 41 views
0

這裏是我的測試:redirect_to驗證失敗後,可能在軌道?

def test_words_with_non_letters_are_rejected 
    visit '/plays' 
    click_link_or_button 'Play New Word' 

    fill_in 'play[word]', :with => 'boom!' 
    click_link_or_button 'Play!' 
    assert page.has_css?("#errors") 

    fill_in 'play[word]', :with => '37nums' 
    click_link_or_button 'Play!' 
    assert page.has_css?("#errors") 

    fill_in 'play[word]', :with => 'ok' 
    click_link_or_button 'Play!' 
    assert_equal '/plays', current_path 
end 

這裏是我的控制器:

class PlaysController < ApplicationController 
    def index 
    @plays = Play.all 
    end 

    def new 
    end 

    def create 
    if params[:play][:word].blank? 
     flash[:error] = 'blank' 
     redirect_to new_play_path 
    else 
     @play = Play.create(plays_params) 
     redirect_to plays_path 
    end 
    end 

    private 

    def plays_params 
    params.require(:play).permit(:word) 
    end 
end 

這裏是我的模型:

class Play < ActiveRecord::Base 

    before_save { self.word = word.downcase } 

    validates :word, presence: true, length: { maximum: 7 } 
    # validates_format_of :word, :with => 

    def letter_scores 
    {"A"=>1, "B"=>3, "C"=>3, "D"=>2, "E"=>1, "F"=>4, "G"=>2, "H"=>4, "I"=>1, "J"=>8, 
    "K"=>5, "L"=>1, "M"=>3, "N"=>1, "O"=>1, "P"=>3, "Q"=>10, "R"=>1, "S"=>1, "T"=>1, 
    "U"=>1, "V"=>4, "W"=>4, "X"=>8, "Y"=>4, "Z"=>10} 
    end 

    def score(setting_hash = {:word_multiplier => :single}) 
    word_multiplier = {:single => 1, :double => 2, :triple => 3} 

    word.upcase.chars.inject(0){|sum, letter| sum + letter_scores[letter]} * word_multiplier[setting_hash[:word_multiplier]] 
    end 
end 

所以我無法寫的validates_format_of驗證的正則表達式的Play模型。此外,我不知道如何驗證失敗後重定向到正確的頁面。我嘗試在創建控制器中寫入兩個redirect_to,但是我得到了一個錯誤消息,其中包含太多redirect_tos。

在其他條件創建操作的,我試過Play.create行之後寫的:

redirect_to plays_path if @play 
flash[:error] "Something when wrong during Play creation" 
redirect_to new_play_path 

我在做什麼錯?

回答

1

Rails的禁止你使用呈現在操作重定向更多然後一次。而且這些方法不會停止執行流程,因此您試圖在示例中執行兩次。相反,您可以在重定向後立即返回返回。像這樣

redirect_to plays_path and return if @play 

而且我建議重構創建方法這樣

def create 
    @play = Play.create(plays_params) 
    if @play.save 
    redirect_to plays_path 
    else 
    flash[:error] = @play.errors.full_messages 
    redirect_to new_play_path 
    end 
end 

所以你可以在閃存所有的驗證錯誤消息。這雖然不是使用Flash的最佳方式,但通常返回特定消息會更好。像

flash[:error] = "Can't save play" 
0

嘗試改變create方法:

def create 
    if params[:play][:word].blank? 
     flash[:error] = 'blank' 
     redirect_to new_play_path 
    else 
     @play = Play.new(plays_params) 
     if @play.save 
     redirect_to plays_path 
     else 
     flash[:error] "Something when wrong during Play creation" 
     redirect_to new_play_path 
     end 
    end 
    end