Search code examples
ruby-on-railsruby-on-rails-4private-methods

Rails best practices : Public methods in model


I'm a newbie and I'm wondering if my app is going to fail is a near future because I don't understand all subtleties of Rails. So I prefer to ask you :-)

I have a User and a Product model, and I want to create a method that could be used like that :

@user.take!(product)

So I wrote in my User model the following line :

def take!(product)
  product.owner = self
end

But if I do that in the private section of my model, it doesn't work. And if I do that in the public section, I don't know if it's recommended. I'm asking myself if it would be better to do something like that in a controller, or in a helper...

Can you enlighten me ?


Solution

  • Writing public methods is fine if they need to be public, it's not a hanging offence or anything like that. The method you describe shouldn't be on the user though - there's no need to put product logic inside the user model, and it's definitely bad to change the product by passing it into a user method. It's also a very short method and so there isn't really very much to be gained by putting it into a method - it just means that if I see take! then I have to go and find where it's defined in order to understand it. You should also only use ! at the end of methods that either might raise an exception or alter the object they are called on.

    Putting this logic in the controller would be fine and much clearer, but in general there's nothing wrong with public methods if they can't be private.