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
I have basic functionality for sending a user to the moon:
#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
Now, I want to add to this by only sending users to the moon if they like to travel.
Is it better to put the if statement in the controller or the model and why?
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(2)
根据 SRP,我会坚持选项 1。
控制器是指挥:它负责逻辑更清晰,可读性更强。
另一种方法是在模型中创建一个命名良好的方法,该方法将处理逻辑并在需要时触发其他方法。
不要忘记测试!
According to the SRP, I'd stick to option 1.
Controller is the conductor: it's responsible for the logic and it's more readable.
An alternative would be to create a well named method in your model which would handle the logic and trigger the other method if needed.
Don't forget the tests!
模型中的状况会更好。
但这取决于要求。
如果您需要在方法调用时显示,则需要在模型中显示。
仅从此操作调用中,您需要显示消息,然后控制器中的条件良好。
Condition in the model will be better.
But here it depends on requirement.
If you need to display whenever the method calls, it would require in the model.
Only from this action call, you require to display message then condition in controller is good.