Rails 模型控制器最佳实践

发布于 2024-11-30 22:44:40 字数 762 浏览 3 评论 0原文

我有将用户发送到月球的基本功能:

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

穿越时光隧道 2024-12-07 22:44:40

根据 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!

眼波传意 2024-12-07 22:44:40

模型中的状况会更好。

但这取决于要求。
如果您需要在方法调用时显示,则需要在模型中显示。
仅从此操作调用中,您需要显示消息,然后控制器中的条件良好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文