Skip to content

Instantly share code, notes, and snippets.

@aliang
Created June 13, 2011 06:25
Show Gist options
  • Save aliang/1022384 to your computer and use it in GitHub Desktop.
Save aliang/1022384 to your computer and use it in GitHub Desktop.
render from model in Rails 3
# yes, sometimes you need to do this. you get pilloried in a forum if you
# ask about it, though!
# this code taken from
# http://wholemeal.co.nz/blog/2011/04/05/rendering-from-a-model-in-rails-3/
class MyModel < ActiveRecord::Base
# Use the my_models/_my_model.txt.erb view to render this object as a string
def to_s
ActionView::Base.new(Rails.configuration.paths.app.views.first).render(
:partial => 'my_models/my_model', :format => :txt,
:locals => { :my_model => self}
)
end
end
@mark-ellul
Copy link

THANK YOU, THANK YOU AND THANK YOU... I had tried many different variations and this is the first one that worked!

@KarlGl
Copy link

KarlGl commented Feb 5, 2014

@nathanbertram Thank you.

@agungyuliaji
Copy link

Thanks Man! Very Help Me

@manoj2411
Copy link

Thanks buddy

@patrickdavey
Copy link

I was doing this recently for injecting a view_context for an Rspec test. I was having issues with the URL helpers even though the default_url_options were set in config/environments/test.rb

ended up adding to the class_eval

action_view.class_eval do 
  include Rails.application.routes.url_helpers
  def default_url_options
    { :host => "example.com" }
  end
  # ...
end

Worked for me.. might possibly help others :)

@zdravko
Copy link

zdravko commented Aug 12, 2016

Excellent! Thank you!
I wonder, though, how fast is this, since we know that rails rendering a view can be slow.
Is there a way to embed this model rendering via helper?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment