【问题标题】:Rails Model Controller Best PracticeRails 模型控制器最佳实践
【发布时间】:2011-08-24 12:29:09
【问题描述】:

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

#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

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    根据SRP,我会坚持选项1。

    Controller 是指挥者:它负责逻辑并且更具可读性。

    另一种方法是在您的模型中创建一个命名良好的方法,该方法将处理逻辑并在需要时触发其他方法。

    别忘了测试!

    【讨论】:

      【解决方案2】:

      模型中的条件会更好。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多