2017-10-06 59 views
-1

在我的Rails代碼庫中,有一個特定方法的動作調用之前,但我無法調用它。RubyOnRails +無法調用IF條件的before_action方法

示例代碼: -

ControllerCode

class HomeController < ApplicationController 
    before_action :set_country, only: [:index, :update] 
    def index 
    puts "Inside Index - #{@country}" 
    end 

    def update 
    if true && book_my_ride 
    puts "Inside Update - BookMyRide" 
    end 
    end 

    def book_my_ride 
    puts "Inside BookMyRide - #{@country}" 
    end 

    def set_country 
    @country = "SampleCountry" 
    end 
end 

當更新方法被調用,因爲之前的動作, - set_country被調用。

但是,當控制達到具有'book_my_ride'的IF條件時 - 系統不會爲book_my_ride調用'set_country'方法。

+0

您是否期望'set_country'在該場景中被調用兩次?這不是它的工作原理。 –

+0

@SergioTulentsev - 明白了你的觀點。錯誤地,我爲before_action添加了book_my_ride – Rubyist

回答

0

您的book_my_ride方法正在執行puts語句,輸出爲零。所以我認爲發生了什麼是你的邏輯真的有說法

if true && nil 
    do something 
end 

這永遠不會返回true,所以執行無法繼續。嘗試添加來自該方法的返回值,並查看執行路徑是否正確繼續。例如:

def book_my_ride 
    puts "Inside BookMyRide - #{@country}" 
    return 'Called book_my_ride' 
    end 

我不知道那些看跌語句是 - 如果他們只是爲了調試,我會嘗試使用任何

Rails.logger.info "debug statement here ..." 

,或者使用返回而不是看跌期權

return "Called #{__method__} --------" 

另一個好的做法是,如果您正在調試,則是通過創建spec測試來驗證控制器的行爲。