Reputation: 4732
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
Upvotes: 0
Views: 283
Reputation: 90
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.
Upvotes: 1
Reputation: 115511
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!
Upvotes: 3