2011-08-24 53 views
0

我有一個用戶發送到月球基本功能:Rails的模式控制器最佳實踐

#Action in a controller 
    def outer_space 
    user = User.find(params[:id]) 
    user.board_rocket_to_the_moon 
    end 


#user model 
def board_rocket_to_the_moon 
    #put on space suit, climb in rocket, etc. 
end 

現在,我想只要他們喜歡旅遊的用戶發送到月球添加到這一點。

將if語句放在控制器或模型中爲什麼更好?

#option 1: Put an if in the controller 
    def outer_space 
    user = User.find(params[:id]) 
    user.board_rocket_to_the_moon if user.likes_to_travel 
    end 


#option 2: Stick the if in the user model 
def board_rocket_to_the_moon 
    if self.likes_to_travel 
    #put on space suit, climb in rocket, etc. 
    return "BLAST OFF" 
    else 
    return "There is no way THIS dude is getting on THAT ship." 
    end 
end 

回答

3

按照SRP,我會堅持選擇1

控制器是導體:它是負責邏輯和它的可讀性更強。

另一種方法是在模型中創建一個命名方法,該方法將處理邏輯並在需要時觸發其他方法。

不要忘記測試!

1

模型中的條件會更好。

但是這取決於需求。 如果您需要在方法調用時顯示,則需要在模型中顯示。 只有從這個動作調用中,你需要顯示消息,然後在控制器中的條件是好的。