我有基本的功能发送用户到月球:
#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
根据SRP,我坚持选择1
Controller是导体:它负责逻辑,而且更容易读懂。
另一种方法是在模型中创建一个命名良好的方法,该方法将处理逻辑并在需要时触发其他方法。
别忘了考试!
模型状态会更好。
但这里取决于需求。如果需要在方法调用时显示,则需要在模型中显示。只有从这个动作调用中,你才需要在控制器中显示消息状态良好。