Have you ever wanted to render a partial to a string from inside a model?

This solution was inspired by this snippet showing how to use view helpers in a controller. It’s clean and simple, no need to mess with ERB or metaprogramming!


class Model

  class Helper < ActionView::Base
    include Singleton
  end
  def help
    Helper.instance
  end

  ...

  def summarize
    ## Note that we have to use the FULL path here!  
    help.render( :partial => "#{RAILS_ROOT}/app/views/notifications/text_order_summary", :object => self )
  end
  alias_method :to_s, :summarize

end

4 Responses to “render a partial from inside a model”

  1. matt Says:

    "Have you ever wanted to render a partial to a string from inside a model?"

    Shouldn't the answer be "no"?

    What use case did you have where this was a good idea?

  2. David Lowenfels Says:

    I have a legacy project where an order has an ordersummary text field that gets frozen into the database at a certain point in order fulfillment. I wanted to render the ordersummary partial into a string and store it on the model.

    Probably the whole system needs further refactoring to store order history in a better way. But in the meantime wanted to move these things from the controller into the model.

  3. matt Says:

    So, is that rendering a bunch of html into that column basically?

    Actually, judging from that view naming -- is that a notifier view? Is this to store the email that gets sent to someone on the model?

  4. David Lowenfels Says:

    No, it wasn't a notifier. It was just plain text actually. I ended up refactoring it as just doing string manipulation in the model. And the same model method can be called from what was before a partial.

Leave a Reply