You may have some reason to break outside MVC model and I won’t give you lecture why you shoudn’t really do it, neither I won’t describe how you will burn in hell for commiting that kind of sin. Instead I will provide a working solution how it can be done. Just as a example of bad pratice :P.
So – how to render view inside model in Rails 3.2?
Let’s start by creating an class that will inherit from AbstractController::Base. You will also need to include bunch of other classes that are required for rendering views, include url_helper, application helper and any other helpers that you may want to use, don’t forget to setup your views path.
# lib/render_abstract.rb class RenderAbstract < AbstractController::Base include AbstractController::Rendering include AbstractController::Layouts include AbstractController::Helpers include AbstractController::Translation include AbstractController::AssetPaths include ActionDispatch::Routing include Rails.application.routes.url_helpers helper ApplicationHelper self.view_paths = "app/views" def show(article) @article = article render :partial => 'articles/show', :layout=>false end end
show method will accept object of class
Article and setup variable accessible to view in standard fashion. Here’s how
Article model looks:
# app/models/article.rb require 'render_abstract.rb' class Article < ActiveRecord::Base def render RenderAbstract.new.show(self) end end
Calling render on article object should now render your view. How about that. Just don’t tell anyone ;-).
In next part I will give you some ideas how can you proxy your Rails application inside existing PHP project. The hunt for witches begins now.