开发者

Rails Model Controller Best Practice

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 th开发者_开发百科e 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜