When to use Helpers vs Model

后端 未结 3 887
醉话见心
醉话见心 2020-12-14 16:02

I\'m new to Rails and just wondering when I should put code into a Helper as opposed to putting the code into the Model.

Is there a \'rule of thumb\' so to speak for

3条回答
  •  醉酒成梦
    2020-12-14 16:24

    It's best to use helpers when the code that the helper is creating is meant to be displayed in the view only. For example if you want to have methods that help create HTML links, they should go in the helper:

    def easy_link user
      link_to(user.name, user)
    end
    

    If your code is business logic it should go in your models. You should also aim to put as much business logic in your models, you don't want this code in your views and controllers. For example, if you want to process an order, that code should go in the model:

    def process
      raise NotReadyToProcess unless ready_to_process?
      raise NotValidPaymentDetails unless valid_payment_details?
      process_payment
    end
    

提交回复
热议问题